【问题标题】:Mongoose findOneAndUpdate Updating Multiple FieldsMongoose findOneAndUpdate 更新多个字段
【发布时间】:2016-09-13 00:25:22
【问题描述】:

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

这是我的 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);
       }
});

【问题讨论】:

    标签: node.js mongodb mongoose mongodb-query


    【解决方案1】:

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

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

    您需要像这样更改您的 update 参数:

    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);
       }
    });
    

    【讨论】:

    • 如果您想在同一个 findByIdAndUpdate 字段中设置 $set 和 $push 怎么办?那么语法会如何呢?
    • @55Cancri 您只需将$push: { &lt;field&gt;: &lt;value&gt;, ..} 添加到“更新”参数:{ $set: { &lt;field1&gt;: &lt;value1&gt;, ... }, $push: { &lt;field&gt;: &lt;value&gt;, ..} }
    • @styvane 你能看看这个 Q stackoverflow.com/a/70171269/15454800
    猜你喜欢
    • 2019-09-27
    • 2020-11-19
    • 2018-04-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-05-06
    • 2016-10-15
    • 2021-04-12
    相关资源
    最近更新 更多