如何覆盖 mongodb 中子文档的数组 属性 (mongoose)
How can I overwrite array property of subdocument in mongodb (mongoose)
我有一个架构
{
name: {type:String}
.....
child : {type: [childSchema], []}
}
和一个子架构
{
x:{type:Number}
y:{type:Number},
options: {type:Array, default}
}
问题是虽然我可以用特定的子 ID 更新单个子属性,但我不能 update/replace 选项数组(只是一个字符串数组),我有
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)
当我 google 我似乎找到了更多关于更新子文档的链接,并且可以找到任何关于替换子文档中的数组的内容,尝试查看 Mongodb & mongoose API 但是除非我忽略了一些东西,否则我找不到在这种情况下有用的东西
谁能指出我正确的方向
尝试更新 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] }
]
}
我有一个架构
{
name: {type:String}
.....
child : {type: [childSchema], []}
}
和一个子架构
{
x:{type:Number}
y:{type:Number},
options: {type:Array, default}
}
问题是虽然我可以用特定的子 ID 更新单个子属性,但我不能 update/replace 选项数组(只是一个字符串数组),我有
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)
当我 google 我似乎找到了更多关于更新子文档的链接,并且可以找到任何关于替换子文档中的数组的内容,尝试查看 Mongodb & mongoose API 但是除非我忽略了一些东西,否则我找不到在这种情况下有用的东西
谁能指出我正确的方向
尝试更新 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] }
]
}