猫鼬findOneAndUpdate更新多个字段 [英] Mongoose findOneAndUpdate Updating Multiple Fields

查看:93
本文介绍了猫鼬findOneAndUpdate更新多个字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

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

推荐答案

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

You are using the $set operator multiple times. The correct syntax for $set is :

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

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

You need to change your update argument 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);
   }
});

这篇关于猫鼬findOneAndUpdate更新多个字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆