Я хочу вставить данные в коллекцию, перед вставкой мне нужно проверить, существуют ли они
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
похоже не содержитresult
вinsertResult.result.ok
Я пытаюсь выполнить console.log
insertResult
(толькоinsertOne
), он содержит `result: {ok: 1, n: 1}`я получил
undefined
?Попробуйте добавить отказоустойчивый код:
if (insertResult && insertResult.result && insertResult.result.ok === 1) {