【发布时间】: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.log
insertResult(仅insertOne),它包含`结果:{ok:1,n:1}` -
我收到了
undefined? -
尝试添加故障保护代码:
if (insertResult && insertResult.result && insertResult.result.ok === 1) {