0

Given is:

var item = {
    email: req.body.email,
    //pw: req.body.pw,
    pw: encpassword,
    timestamp: Date.now()
};
var mailAddress = item.email;
var resultArrayEmail = [];

MongoClient.connect(url, { useNewUrlParser: true }, function(err, client) {
    // assert.equal(null, err);


    const db = client.db(dbName);

    //####### Proof of exist

    var cursor = db.collection('userdata').find();
    var cursorCheck = db.collection('userdata').findOne({"email": mailAddress});

    if (cursorCheck.length > 0){
        console.log('Item exists');
    }else{
        db.collection('userdata').insertOne(item, function(err, result) {
            assert.equal(null, err);
            client.close();
        }); 
        // cursor.forEach(el => console.log(el.email)); => Returns all emailadresses within a collection
        console.log(item);
        console.log('inserted!');           
    }   
    res.redirect('/register');
});

Using indexOf to filter an array I have tried it like this and it works fine, but it seems a mongoDB-collection is not an array of objects... -> So it not works in condition to this solution.

How to check the "field" email if an emailadrress already exists?

daisyDuck
  • 301
  • 1
  • 2
  • 8

2 Answers2

2

findOne have callback function you need to check condition inside the callback function Like

    db.collection("userdata").findOne({ email: mailAddress }, function(error, result) {
    if (!error) {
      if (result) {
        console.log("Item exists");
      } else {
        console.log("Item not exists");
      }
    } else {
      console.log("MongoDB error");
    }
  });
Hiren Ghodasara
  • 336
  • 1
  • 9
  • empty objects are truthy values and findOne returns empty object when the filter doesnt match. Hence it should be `if(Object.getOwnPropertyNames(result).length !== 0)` to check if `result` object is empty. – Arbaz Siddiqui Sep 24 '18 at 13:16
0

use the following check

if (result !== null) {}

or

if (result === null) {}
Zahirul Haque
  • 1,599
  • 17
  • 22