2015-03-31 73 views
1

我有一個架構我如何可以覆蓋在MongoDB中(貓鼬)子文檔的數組屬性

{ 

    name: {type:String} 
    ..... 
    child : {type: [childSchema], []} 

} 

和一個孩子的模式

{ 
    x:{type:Number} 
    y:{type:Number}, 
    options: {type:Array, default} 
} 

的問題是雖然我可以更新與個別孩子的屬性一個特定的孩子ID,我不能更新/替換選項陣列(只是一串字符串),我有

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']} 
    } 

我認爲(但我不確定),也許我不能在這個級別

當我谷歌我似乎使用任何的$函數($組,$所有)找到更多關於更新子文檔的鏈接,可以找到任何東西在替換子文檔中的數組,嘗試尋找MongoDB &貓鼬API,但除非我忽略了一些東西,我找不到任何東西在這種情況下工作

任何人都可以指向正確的方向

+0

具有u嘗試不使用'$'i.e- child.options {} – 2015-03-31 12:01:30

回答

3

嘗試升級就像從蒙戈外殼下面的例子:

> 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] } 
    ] 
}