【问题标题】:Mongoose update succeeds but returns undefinedMongoose 更新成功但返回 undefined
【发布时间】: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 中,两个变量名称都相同,docdoc 可能会起作用,但这是不好的做法。

标签: mongoose promise


【解决方案1】:

.update 不要返回 Promise 它使用 callback

Post.update({_id: doc._id}, {$set: posts[idx]}, (err) => {
    if (err) {
        console.log("Failed to save: " + posts[idx].title);
        return console.error(err);
    }
    console.log("Succeeded to update: " + posts[idx].title);
    savePostsInOrder(++idx, limit);
});

【讨论】:

    【解决方案2】:

    我已经解决了。

    如果我使用回调参数处理异常,update 不会返回任何 mongoose 对象,所以我必须使用 catch 除了回调参数。

    我不知道为什么update 返回undefinedsave 在相同的条件下返回。

    无论如何,修改后的代码如下所示。

    Post.update({_id: doc._id}, {$set: posts[idx]})
        .then(() => {
            console.log("Succeeded to update: " + posts[idx].title);
            savePostsInOrder(++idx, limit);
        }).catch((err) => {
            console.log("Failed to save: " + posts[idx].title);
            return console.error(err);
        });
    

    【讨论】:

      猜你喜欢
      • 2023-03-20
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2016-06-28
      • 2016-03-23
      • 2013-11-23
      • 2018-08-18
      • 2017-06-11
      相关资源
      最近更新 更多