node.js Mongoose findOneAndUpdate 更新多个字段

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/37267042/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 20:12:24  来源:igfitidea点击:

Mongoose findOneAndUpdate Updating Multiple Fields

node.jsmongodbmongoosemongodb-query

提问by pdace

The findOneAndUpdate method doesn't work properly. I'm trying to update all the fields all at once but it's only updating (setting) the last field. It's always only the last field. Can someone tell me what I'm doing wrong or what can I do to have the expected effect?

findOneAndUpdate 方法无法正常工作。我试图一次更新所有字段,但它只更新(设置)最后一个字段。它始终只是最后一个字段。有人可以告诉我我做错了什么或者我该怎么做才能达到预期的效果?

This is my findOneAndUpdate code:

这是我的 findOneAndUpdate 代码:

Book.findOneAndUpdate({_id:bookId},{$set:{"name": name},$set:{"genre": genre},$set:{"author": author},$set:{"similar": similar}}).exec(function(err, book){
       if(err){
           console.log(err);
           res.status(500).send(err);
       } else {
            res.status(200).send(book);
       }
});

回答by styvane

You are using the $setoperator multiple times. The correct syntax for $setis :

$set多次使用该运算符。的正确语法$set是:

{ $set: { <field1>: <value1>, ... } }

You need to change your updateargument like this:

您需要像这样更改更新参数:

Book.findOneAndUpdate({ "_id": bookId }, { "$set": { "name": name, "genre": genre, "author": author, "similar": similar}}).exec(function(err, book){
   if(err) {
       console.log(err);
       res.status(500).send(err);
   } else {
            res.status(200).send(book);
   }
});