【问题标题】:Meteor/Mongo, push into an array inside an object inside an arrayMeteor/Mongo,推入数组内对象内的数组
【发布时间】:2016-07-26 03:00:32
【问题描述】:

我正在尝试自学 Meteor 和 Mongo。我的 Meteor 方法中有一个特殊的插入,让我发疯。

我的文档对象如下所示:

{
    _id
    name: "name",
    stuff: {},
    array: [
        {
            id: 0,
            target:[
                {
                    id: 0,
                    name: "1"
                },{
                    id: 1,
                    name: "2"
                }
            ]
        },{
            id: 1,
            target:[
                {
                    id: 0,
                    name: "A"
                },{
                    id: 1,
                    name: "B"
                }
            ]
        }
    ],
}

我正在尝试将对象添加到目标数组中,该数组位于数组数组内的对象内。

根据我在此处看到的有关堆栈溢出的一些情况,我在几天内尝试了多种不同的方法。最近的尝试是:

Documents.update({_id: id, 'array.id': arrayId}, {$addToSet:{'array.$.target': objectToInsert}},{upsert: false, multi: false})

如果有人能指出我正确的方向,我将不胜感激。

【问题讨论】:

    标签: mongodb meteor


    【解决方案1】:

    我不知道 mongo 查询可以做这样的事情,但可以按如下方式完成

    let theArray=Document.findOne({_id:id}).array,
    arrayOfIds=_.pluck(theArray,"id"),
    index=_.indexOf(arrayOfIds,arrayId),
    theArray[index].target.push(objectTobeInserted)
    

    现在用修改后的数组更新文档

    Document.update({_id:id},{$set:{array:theArray})
    

    如果不了解_.pluck和_.indexOf,可以参考underscorejs

    【讨论】:

    • 这行得通,除了一些非常小的语法错误。非常感谢。
    【解决方案2】:

    似乎这可能是您进行更新的位置的问题。如果这是在客户端上,请参见此处:

    Update an subdocument contained in an array contained in a MongoDB document

    解决方案是将其移至服务器。

    另外,您可能想在这里查看 $addToSet 和 $push 之间的区别MongoDb: Difference between $push/$addtoset

    如果这不在客户端并且更改为推送并不能解决您的问题,您能否在您的问题中添加错误是什么。

    【讨论】:

      猜你喜欢
      • 2014-08-10
      • 2015-11-14
      • 2016-04-23
      • 2014-11-12
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-15
      • 2017-09-26
      相关资源
      最近更新 更多