如何在 MongooseJS 中使用 {upsert: true} 获取 findOneAndUpdate 的创建对象?

How do you get the created object of a findOneAndUpdate with {upsert: true} in MongooseJS?

我在做什么:

Book.findOneAndUpdate(
    {_id: id_from_api},
    {$set: bookObj},
    {upsert: true},
    function (err, book) {
        handleError(err);
        console.log(book);
    }
);

我希望 book 是一个 book 文档,但它只有存在时才是文档,而不是因为 upsert 为真而创建时。

我的问题是:如何获取新建的书籍文档?

更新 只需将选项 new 显式设置为 true

Book.findOneAndUpdate(
    {_id: id_from_api},
    {$set: bookObj},
    {upsert: true, new: true},
    function (err, book) {
        handleError(err);
        console.log(book);
    }
);

您可以预先实例化书籍对象,如下所示:

var book = new Book(bookObj);

Book.findOneAndUpdate(
    {_id: book._id},
    {$set: book.toObject()},
    {upsert: true},
    function (err, result) {
        handleError(err);
        console.log(result ? "Updated existing object:" : "New object created:");
        console.log(result || book);
    }
);

findOneAndUpdate 的文档中有一个名为 new 的选项,它曾经默认为 true

new: bool - if true, return the modified document rather than the original.
defaults to false (changed in 4.0)