【问题标题】:MongoDB TypeError: Cannot read property 'result' of undefinedMongoDB TypeError:无法读取未定义的属性“结果”
【发布时间】:2018-04-08 09:35:19
【问题描述】:

我想将数据插入到集合中,在插入之前我需要检查它是否存在

  collection.find({sno: req.body.sno}).toArray((err, result)=> {

    if (result.length > 0) {
      flag = false;
      callback(flag);
    }
    else {
      console.log(result.length);
      collection.insertOne({sno: req.body.sno, password: req.body.password}, (err, insertResult)=> {
        if (insertResult.result.ok === 1) {  
          flag = true;
        }
        callback(flag);
      });
    }
  });

如果sno 不存在,我得到了

0
/node_modules/mongodb/lib/utils.js:123
process.nextTick(function() { throw err; });
                              ^

TypeError: Cannot read property 'result' of undefined

但是,如果sno存在或只有collection.insertOne(删除collection.find),它就可以工作。

如何解决这个问题?请给我一些帮助。

好像是回调函数参数的问题??

collection.find({xx:xx}).toArray((err, result)=> {
    collection.insertOne({...}),(err)=>{}  //can't use res??
&&
collection.inserOne({...}),(err,res)=>{
  console.log(res.result); // {ok:1,n:1}
}

【问题讨论】:

  • 检查正确吗? insertResult 似乎在insertResult.result.ok 中不包含result
  • 我尝试console.loginsertResult(仅insertOne),它包含`结果:{ok:1,n:1}`
  • 我收到了undefined?
  • 尝试添加故障保护代码:if (insertResult && insertResult.result && insertResult.result.ok === 1) {

标签: node.js mongodb


【解决方案1】:

尝试记录错误,看看你得到了什么。 无论如何,如果您想知道光标的长度,您不必将其转换为数组,请使用cursor.count()。在你的情况下:

 collection.find({sno: req.body.sno}).count()

另外,如果您对使用 Promise 感到满意,我建议您采用这种方法。

 collection.find({sno: req.body.sno})
.then(result => {
  if (result.count() < 1) throw new Error() 
   })
 .then(() =>{
 // insert
 flag = true;
 })
 .catch(err => {
 flag = false; 
})

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-11-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多