Search code examples
mongoosemongoose-schemamongoose-populate

Mongoose: How to update sub embedded document array?


Here is my Schema

const NetworkSchema = new Schema({
 user: {
 type: Schema.Types.ObjectId,
 ref: 'user'
},
name: {
  type: String
},
friendrequests: [
{
  user: {
    type: Schema.Types.ObjectId,
    ref: 'user'
  },
  name: {
    type: String
  },
  status: {
    type: String,
    default: 'pending'
  },
  date: {
    type: Date,
    default: Date.now
  }
}
],

});

I want to update my sub embedded document friendrequest using it's _id. I'm still new to mongoose please help. Thanks


Solution

  • Okay managed to update sub embedded document using updateOne

      const network = await Network.updateOne(
       {
         user: req.user.id,
         'friendrequests._id': req.params.friendrequest_id
       },
       {
         $set: { 'friendrequests.$.status': 'accepted' }
       }
      );
    

    Referrence: MongoDB: How do I update a single subelement in an array, referenced by the index within the array?