How can I update the Mongoose subtask in the instance method?

I have a Mongoose document with an array of subdocuments like this:

var RegionSchema = new Schema({ "metadata": { "regionType": String, "name": String, "children": [{ "name": String, "childType": String, "id": Schema.ObjectId }], "parent": Schema.ObjectId }, "data": [DataContainer] }); 

In the DataContainer schema, I want to create an instance method that can update data internally.

For clarity , I want to be able to search for Region , find the DataContainer inside the data array and call something like dataCont.update() , in which the DataContainer instance can do this.save() . Is it possible?

Performance

 this.save(function(err, saved) { console.log(saved) callback(err, saved); }); 

inside the instance method of the DataContainer undefined is output. The callback hit though.

0
source share
1 answer

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) { // ... }); }); 
+1
source

All Articles