我有一个架构
{
name: {type:String}
.....
child : {type: [childSchema], []}
}
和子模式
{
x:{type:Number}
y:{type:Number},
options: {type:Array, default}
}
问题是虽然我可以使用特定的子ID更新单个子属性,但我无法更新/替换Options数组(只是一个字符串数组),我有
parent.findOneAndUpdate({
_id: id,
status: 'draft',
child: {
$elemMatch: {
_id: childId
}
}
}, {
$set: {
child.$.x : newX,
child.$.y : newy,
child.$.options : ['option1', 'option2']
}
}).lean().exec()
我也试过
$set: {
'child.$.x' : newX,
'child.$.y' : newy,
'child.$.options' : { '$all' ['option1', 'option2']}
}
我认为(但我不确定)也许我不能在这个级别使用任何$函数($ set,$ all)
当我谷歌我似乎找到更多关于更新子文档的链接,并可以找到任何替换子文档中的数组,尝试查看Mongodb& mongoose API,但除非我忽略了一些我无法找到任何可以在这种情况下起作用的东西
任何人都可以指出我正确的方向
答案 0 :(得分:3)
尝试使用mongo shell中的以下示例中的更新:
> db.test.drop()
> db.test.insert({
"_id" : 0,
"children" : [
{ "_id" : 1, "x" : 1, "y" : 2, "options" : [1, 2, 3] },
{ "_id" : 2, "x" : 5, "y" : 8, "options" : [1, 6, 2] }
]
})
> db.test.update({ "_id" : 0, "children._id" : 1 },
{ "$set" : { "children.$.x" : 55, "children.$.y" : 22, "children.$.options" : [9, 8, 7] } }
)
> db.test.findOne()
{
"_id" : 0,
"children" : [
{ "_id" : 1, "x" : 55, "y" : 22, "options" : [9, 8, 7] },
{ "_id" : 2, "x" : 5, "y" : 8, "options" : [1, 6, 2] }
]
}