mongoDB mongose部分更新对象

sczxawaw  于 2023-03-07  发布在  Go
关注(0)|答案(2)|浏览(95)

我有这个模型。User.js

methods: {
      type: [String],
      required: true,
    },
local: {
      email: {
        type: String,
        lowercase: true,
      },
      password: {
        type: String,
      },
      id: Number,
      title: {
        type: String,
        enum: ['Ms', 'Mrs', 'Mr', 'Dr'],
        default: 'Mr',
      },
      firstName: String,
      lastName: String,
      role: {
        type: String,
        default: 'user',
      },
      permissions: [String],
    },
    status: { type: Boolean, default: true },

请注意,本地字段有很多属性。假设我只想更新一些属性。即标题,姓氏和角色。

{
lastName:'virat',
role:'manager',
title:'Mr'
}

我试着这样更新它

const filter = { _id: req.params.id };
    const update = {
      local: {
        lastName: "virat",
        role: "manager",
        title: "Mr",
      },
    };

    await User.findOneAndUpdate(filter, update);

更新后,本地只有3个字段,其他字段已经没有了。我如何更新某些字段而不丢失其他字段?
任何帮助!提前感谢!=)

blmhpbnm

blmhpbnm1#

试试这个:

const filter = { _id: req.params.id };
const update = {
  "local.lastName": "virat",
  "local.role": "manager",
  "local.title": "Mr"
};

await User.findOneAndUpdate(filter, update);
e0bqpujr

e0bqpujr2#

user
    .updateMany(
      { "local.id": id },
      {
        $set: {
          "local.$.title": title,
          "local.$.role": role, 
          "local.$.lastName":lastName
        },
      },
      {
        new: true,
      }
    ).then((update)=>{ response}).catch((err)=>{ err-response})

我希望你能理解我的React

相关问题