0
如何根據以下Schema更新array1.array2.status
?在Mongoose中更新非常嵌套的文檔
var SomeSchema = new mongoose.Schema({
status: Boolean,
array1: [{
array2[{
status: boolean
}]
}]
})
如何根據以下Schema更新array1.array2.status
?在Mongoose中更新非常嵌套的文檔
var SomeSchema = new mongoose.Schema({
status: Boolean,
array1: [{
array2[{
status: boolean
}]
}]
})
首先,這將是很好重新組織架構成子模式是這樣的:
var valueItemSchema = new mongoose.Schema({
_id: Number,
status: Boolean
});
var subItemSchema = new mongoose.Schema({
_id: Number,
array2: [valueItemSchema]
});
/*
//or this if you dont want _id in your nested documents
var valueItemSchema = new mongoose.Schema({
status: Boolean
}, {
_id: false
});
var subItemSchema = new mongoose.Schema({
array2: [valueItemSchema]
}, {
_id: false
});
*/
var itemSchema = new mongoose.Schema({
status: Boolean,
array1: [subItemSchema]
});
var valueItem = db.model('ValueItem', valueItemSchema);
var SubItem = db.model('SubItem', subItemSchema);
var Item = db.model('Item', itemSchema);
//create a new item
var myItem = new Item({
status: true,
array1: new SubItem({
_id: 0,
array2: [new valueItem({
_id: 0,
"status": true
}), new valueItem({
_id: 1,
"status": false
}), new valueItem({
_id: 2,
"status": true
})]
})
});
然後,您可以更新array2
通過_id
的元素:
Item.findOne({
status: true
}).exec(
function(err, result) {
result.array1.id(0).array2.id(0).status=false;
result.save(function(err) {
console.log(result)
});
}
);
或者如果您不想在索引中更新_id
,請按索引更新:
Item.findOne({
status: true
}).exec(
function(err, result) {
result.array1[0].array2[0].status=false;
result.save(function(err) {
console.log(result)
});
}
);
Here是一個完整的演示