簡體   English   中英

如何在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更新單個子屬性,但我無法更新/替換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,但除非我忽略了一些東西,我找不到任何可以在這種情況下工作的東西

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

嘗試使用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] }
    ]
}

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM