如何在实例方法中更新Mongoose子文档? [英] How can I update a Mongoose subdocument in an instance method?
问题描述
我有一个Mongoose文档,其中包含一系列子文档,如下所示:
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]
});
在DataContainer
模式中,我想创建一个实例方法来更新其内部的数据.
In the DataContainer
schema, I want to make an instance method that can update the data inside itself.
为清楚起见,我希望能够查找Region
,在data
数组中找到一个DataContainer
,并调用类似dataCont.update()
的名称,其中this.save()
.这可能吗?
For clarity, I want to be able to look up a Region
, find a DataContainer
inside the data
array and call something like dataCont.update()
, in which the DataContainer
instance can do a this.save()
. Is this possible?
做
this.save(function(err, saved) {
console.log(saved)
callback(err, saved);
});
在DataContainer
实例方法内部的
打印出undefined
.回调被击中.
inside a DataContainer
instance method prints out undefined
. The callback is hit though.
推荐答案
如果data
属性是子文档,则可以轻松使用populate
并对其进行更新:
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) {
// ...
});
});
这篇关于如何在实例方法中更新Mongoose子文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!