margherita pizza
margherita pizza

Reputation: 7145

mongoDB monggose partly update an object

I have this model. 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 },

Please note that local field has many properties. Say I only want to update few properties. namely title,lastName and role.

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

I tried to update it like this

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

    await User.findOneAndUpdate(filter, update);

After the update, local has only 3 fields and other fields have been gone. How do I update certain fields without losing the other fields?

Any help! Thanks in advance! =)

Upvotes: 1

Views: 31

Answers (2)

bho0t
bho0t

Reputation: 26

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

I hope you'll understand the response thing

Upvotes: 0

Dheemanth Bhat
Dheemanth Bhat

Reputation: 4452

Try this:

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

await User.findOneAndUpdate(filter, update);

Upvotes: 1

Related Questions