查看我的以下示例模式。
const ParentSchema = new mongoose.Schema({
id:String
name:String
age:Number
child:[{
id:String,
name:String,
age:Number}]
})
const collectionName = mongoose.model("parent", ParentSchema)
现在我想为每个人的特定身份增加孩子和父母的年龄。两者同时进行。我尝试使用以下查询
collectionName.update({'_id':new mongoose.Types.ObjectId("59198a3e73ae303f97e97e8f"),'child._id':new mongoose.Types.ObjectId("59198a3e73ae303f97e97eds")},
{$inc:{'age':1},$inc:{'child.$.age':1}},function(err,res){
if(err){
console.log(err.message)
}else{
console.log(res)
}
以上查询效果很好,但它只更新了孩子的年龄而不是父年龄。现在我不确定应该如何模拟我的查询来更新它们?
答案 0 :(得分:3)
此查询适用于我:
db.collection.update({
'_id': new mongoose.Types.ObjectId("59198a3e73ae303f97e97e8f"),
'child.id': A SPECIFIC ID
},
{
$inc: { 'age': 1, 'child.$.age': 1 }
});
您的查询不起作用,因为$运算符在从嵌套数组中增加适当的子项之前需要一个条件来验证。如果你想深化,这里是official documentation。