【发布时间】:2018-07-19 23:08:36
【问题描述】:
Talk 很便宜,所以我先给你看我的代码。
const savePostsInOrder = (idx, limit) => {
if (idx >= limit) {
console.log("Save completed.");
return;
}
Post.find({
title: posts[idx].title,
belongToMajor: posts[idx].belongToMajor,
belongToMinor: posts[idx].belongToMinor,
}).then(
(doc) => {
doc.map((doc) => {
if (posts[idx].content !== doc.content) {
/* if there is (update) */
Post.update({_id: doc._id}, {$set: posts[idx]}, (err) => {
if (err) {
console.log("Failed to save: " + posts[idx].title);
return console.error(err);
}
}).then(() => {
console.log("Succeeded to update: " + posts[idx].title);
savePostsInOrder(++idx, limit);
});
}
});
}
);
}
Post 如您所见,是一个猫鼬对象。
posts 是对象的全局列表,我想用posts 的对象更新我的 mongodb 文档。
问题是,Post.update({_id: doc._id}, {$set: posts[idx]}, callback) 返回undefined,而不是承诺。 update 成功更新现有 db 模型,但返回 undefined。任何人都可以告诉我解决方案或原因吗?
这是我收到的错误消息。
(节点:3338)UnhandledPromiseRejectionWarning:未处理的承诺拒绝(拒绝 id:1):TypeError:无法读取未定义的属性“then”
【问题讨论】:
-
那是因为它是
asynchronous call并且您将其视为同步的,这就是您可能会变得未定义的原因,您应该使用async/await并且看起来您没有从函数中返回任何内容 -
update没有与find不同的返回值吗?那么,我应该返回什么样的数据呢?我应该自己做一个承诺对象吗? -
好吧,我误解了猫鼬查询,但我认为
update必须有then功能。看看这个链接。 mongoosejs.com/docs/promises.html#queries-are-not-promises -
是的,这是正确的,但是在您完成更新
doc之后,您还必须返回一些success param,而您不是,这就是您收到错误的原因 -
并且在您的
map中,两个变量名称都相同,doc和doc可能会起作用,但这是不好的做法。