Park
Park

Reputation: 79

Mongoose update entire nested elements

I am using mongoose and MongoDB. Is there any way to update the entire schedule array in the schema? or do I have to use a for loop and insert one by one? My req.body is an array to replace the entire schedules array object.

[{"_id":"1","description":"hi","time":"Jul 29, 2020 8:55 PM","url":"aaa.com"},{"_id":"2","description":"hi","time":"Jul 29, 2020 8:58 PM","url":"bbb.com"},{"_id":"3","description":"hi"}]

here is my schema.

const schedule = new mongoose.Schema({
  user_id: Number,
  schedules: [{
    description: String,
    time: String,
    url: String
  }]
});

Thank you.

Upvotes: 0

Views: 109

Answers (2)

Shyam Pillai
Shyam Pillai

Reputation: 351

If you're using mongoose, we can avoid using $set. @jitendra's answer is a pure mongodb query which you could run in the mongo shell.

You can refer to this link https://mongoosejs.com/docs/api.html#model_Model.findOneAndUpdate . As the link says,

var query = { name: 'borne' };
Model.findOneAndUpdate(query, { name: 'jason bourne' }, options, callback)

// is sent as
Model.findOneAndUpdate(query, { $set: { name: 'jason bourne' }}, options, callback)

This helps prevent accidentally overwriting your document with { name: 'jason bourne' }.

So in your case we just need to write :

Schedule.findOneAndUpdate({_id: "id_of_object"}, {schedules: req.body});

That should do it for you. But internally, as the doc says, it is being sent as:

Schedule.findOneAndUpdate({_id: "id_of_object"}, {$set: {schedules: req.body}})

Ofcourse this assumes that your req.body consists of the array of schedules only. Most likely you're sending it as an object from the front end so maybe it's req.body.object_name . Up to you.

Upvotes: 1

Jitendra
Jitendra

Reputation: 3185

You can update the entire schedule array by using $set , try as follow:

db.collection.update({query},{ $set: { schedules: req.body } },{option});

Here your req.body should be the array with same keys as per defined in your schema.

Upvotes: 0

Related Questions