如何覆盖MongoDB中的子文件的数组属性(mongoose)
我有一个Schema
{ name: {type:String} ..... child : {type: [childSchema], []} }
和一个子模式
{ x:{type:Number} y:{type:Number}, options: {type:Array, default} }
问题是,虽然我可以用一个特定的孩子ID更新个人的儿童属性,我不能更新/replace选项数组(只是一个string数组),我有
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)
当我谷歌我似乎find更多的链接关于更新子文档,可以find任何东西在一个子文档中replace数组,尝试在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] } ] }