Node.js 猫鼬;更新;除非我使用“不起作用”;。然后";
我曾尝试使用mongoose在我的DB上编辑实例,update和updateOne函数对我不起作用,除非我在函数之后使用它 此代码适用于:Node.js 猫鼬;更新;除非我使用“不起作用”;。然后";,node.js,mongodb,mongoose,Node.js,Mongodb,Mongoose,我曾尝试使用mongoose在我的DB上编辑实例,update和updateOne函数对我不起作用,除非我在函数之后使用它 此代码适用于: Word.findOne({word:req.body.word}).then(function (res) { if (res === null) { const new_word = new Word({ word: req.body.word, translate: req.bo
Word.findOne({word:req.body.word}).then(function (res) {
if (res === null) {
const new_word = new Word({
word: req.body.word,
translate: req.body.translation
});
new_word.save();
}
else
res.updateOne({translate: req.body.translation}).then(function () {});
});
此代码不起作用:
Word.findOne({word:req.body.word}).then(function (res) {
if (res === null) {
const new_word = new Word({
word: req.body.word,
translate: req.body.translation
});
new_word.save();
}
else
res.updateOne({translate: req.body.translation});
});
提前感谢:)也许可以尝试使用
.exec
res.updateOne({translate: req.body.translation}).exec();
也许可以尝试使用
.exec
res.updateOne({translate: req.body.translation}).exec();
mongoose find、update、delete方法返回一个承诺,因此您需要then block,也需要save方法也返回承诺,您还需要将then block添加到那里。mongoose查询返回承诺,承诺在您不使用
之前不会得到解决。然后使用它。它将始终处于pending
状态。但在回答您的问题后,“save”功能在没有“then”的情况下运行良好吗@LiorSwisa:我知道这并不能回答问题,但只要检查一下,当你有机会进行upsert时,你真的需要在两次DB调用中执行此操作吗?这样,你将只需要一次DB调用!!但对于您的实际问题,请检查此项,因为.then()类似于回调,这应该是您可能要寻找的答案::mongoose find,update,delete方法返回一个承诺,因此您需要然后阻止,还保存方法还返回承诺,您还需要向其中添加then块。Mongoose查询返回PROMITE,并且PROMITE在您不使用之前不会得到解析。然后将其与一起使用。它将始终处于pending
状态。但在回答您的问题后,“save”功能在没有“then”的情况下运行良好吗@LiorSwisa:我知道这并不能回答问题,但只要检查一下,当你有机会进行upsert时,你真的需要在两次DB调用中执行此操作吗?这样,你将只需要一次DB调用!!但对于您的实际问题,请检查此项,因为.then()类似于回调,这应该是您可能要寻找的答案::而不是答案.exec
仅用于返回完整的承诺,而不是答案.exec
仅用于返回完整的承诺。