Skip to content Skip to sidebar Skip to footer

How Can I Update A Mongoose Subdocument In An Instance Method?

I have a Mongoose document with an array of subdocuments like this: var RegionSchema = new Schema({ 'metadata': { 'regionType': String, 'name': String, 'children': [{

Solution 1:

If the data property is a subdocument you can easily use populate and update it:

Region.findOne({ _id: regionId })
  .populate('data')
  .exec(function (err, region) {
    // ...

    var data = region.data, // data container
        dataItem = data[0];

    dataItem.property = 'some value';
    dataItem.save(function (err, item) {
      //...
    });

    // or
    dataItem.update({ $set: { property: 'some value' }}, function (err, item) {
      // ...
    });

  });

Post a Comment for "How Can I Update A Mongoose Subdocument In An Instance Method?"