skip to Main Content

I am trying to update an object inside of an array in mongoDB. But what happens is — it returns the correct updated result, BUT it does not update the actual document in DB.

It is weird, I am using this query from past so many months and it is behaving weirdly of sudden.

Schema:

{
  name: String,
  donations: [
    {
      assigned: Boolean
    }
  ]

}

My Query:

const updated = await DonationModel.findOneAndUpdate(
  {
    _id:'document Object Id',
    'donations._id': 'Object Id of donation Object'
  },
  {
    'donations.$.assigned': true,
  },
  {
    new: true
  }
);

// Here I get the updated result
// But this is NOT updated in DB.
console.log(updated); 

2

Answers


  1. Try to add upsert: true to bottem of to new: true.

    Like this:

    const updated = await DonationModel.findOneAndUpdate(
      {
        _id:'document Object Id',
        'donations._id': 'Object Id of donation Object'
      },
      {
        'donations.$.assigned': true,
      },
      {
        new: true,
        upsert: true
      }
    );
    
    // Here I get the updated result
    // But this is NOT updated in DB.
    console.log(updated); 
    Login or Signup to reply.
  2. It looks as though you’re missing the donations._id in your donations object in the schema.

    Also, use {upsert: true} instead of new, unless you mean returnNewDocument?

    Working playground example: https://mongoplayground.net/p/0bcjdi5st40

    Positional update documentation is here

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search