【问题标题】:How to check if an object exists?如何检查对象是否存在?
【发布时间】:2018-09-25 04:15:28
【问题描述】:

给出的是:

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 我已经这样尝试过了,它工作正常,但似乎 mongoDB-collection 不是一个对象数组...... -> 所以它不适用于这个解决方案。

如果电子邮件地址已经存在,如何检查“字段”电子邮件?

【问题讨论】:

  • 你想做什么,怎么没用?
  • findOne 将返回对象而不是数组,因此 cursorCheck.length > 0 将不起作用。
  • 使用count() 代替这里MongoDB count collection Node.js

标签: node.js mongodb


【解决方案1】:

findOne 有回调函数,你需要检查回调函数里面的条件 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");
    }
  });

【讨论】:

  • 空对象是真值,当过滤器不匹配时 findOne 返回空对象。因此它应该是if(Object.getOwnPropertyNames(result).length !== 0) 来检查result 对象是否为空。
【解决方案2】:

使用以下检查

if (result !== null) {}

if (result === null) {}

【讨论】:

    猜你喜欢
    • 2011-09-26
    • 1970-01-01
    • 2012-07-27
    • 2014-09-15
    • 2017-10-13
    • 1970-01-01
    • 1970-01-01
    • 2016-04-02
    • 1970-01-01
    相关资源
    最近更新 更多