我想使用 findOneAndUpdate()
方法创建不存在的文档,或更新存在的文档。考虑以下代码:
SampleComment = new Comment({
id: '00000001',
name: 'My Sample Comment',
...
})
我试图找出 SampleComment
是否已经存在,如果存在,则更新它,否则创建它:
Comment.findOneAndUpdate(
{ id: SampleComment.id },
{ SampleComment }, // <- NOT PASSING THE OBJECT
{ upsert: true, setDefaultsOnInsert: true },
function(error, result) {
...
});
我试图在第二个参数中将模型实例作为对象传递,但结果只返回模型的默认值。文档本身也是如此。
如何在第二个参数中正确传递整个对象 SampleComment
?
最佳答案
当您使用 Document
对象调用 findOneAndUpdate()
作为更新对象并使用 { SampleComment }
时,实际发生了什么?将其重新解构为 SampleComment : {...}
。
然后 Mongoose 将查看您的数据库文档中是否有任何名为 SampleComment
的属性,没有找到,然后什么也不做。返回给您一个没有任何改变的文档。
要解决此问题,您可以先使用 Mongoose 的 toObject()
方法将您的 Document 转换回普通更新对象,然后删除 _id
(因为该属性是不可变的,你不想用更新替换它)然后用你现有的 findOneAndUpdate()
方法保存它。例如:
let newComment = SampleComment.toObject();
delete newComment._id;
Comment.findOneAndUpdate(
{ id: SampleComment.id },
newComment,
{ upsert: true, setDefaultsOnInsert: true },
function(error, result) {
...
}
);
然后您可以在数据库中看到更新后的文档。要在您的 result
中接收更新的文档,您还需要将选项 { new: true }
传递给您的选项对象。
这是 Mongoose 的 toObject() 的链接记录方法文档。
关于javascript - MongoDB/ Mongoose : Updating entire document with findOneAndUpdate(),我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37823774/