在嵌套数组 mongodb nodejs 中插入对象

Insert object in nested array mongodb nodejs

所以我试图在参数中插入一个对象,但没有成功。我的 mongodb 结构如下所示:

[
    {
        "_id": "04",
        "name": "test service 4",
        "id": "04",
        "version": "0.0.1",
        "title": "testing",
        "description": "test",
        "protocol": "test",
        "operations": [
            {
                "_id": "99",
                "oName": "test op 52222222222",
                "sid": "04",
                "name": "test op 52222222222",
                "oid": "99",
                "parameters": {},
                "description": "testing",
                "returntype": "test"
            },
            {
                "_id": "58",
                "oName": "test op 52222222222",
                "sid": "04",
                "name": "test op 52222222222",
                "oid": "58",
                "parameters": {},
                "description": "testing",
                "returntype": "test"
            }
        ]
    }
]

我希望能够将一个对象添加到具有名称、ID 和类型等基本详细信息的参数中。我不完全确定如何解决这个问题,因为在参数部分之前我已经实施了所有其他 CRUD 操作。我应该如何去完成这个?我知道 mongodb 在尝试将某些内容插入数组中的数组时会遇到问题,因此如果有人对我如何完成此操作有任何建议,我将不胜感激。谢谢

其中一个问题是我无权访问根对象的 _id,但我有插入参数的操作的 _id。因此,我试图使用此代码插入参数:

collection.update({"operations":{"$elemMatch": {"oid": oid}}}, {'$addToSet':{"operations.parameters":  {name: "test"} }}, {safe:true}, function(err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(result[0]);
        }
    });

虽然这不起作用。

这是因为您需要使用positional operator,我从link复制的示例与您的情况几乎相同:

db.students.update(
   { _id: 4, "grades.grade": 85 },
   { $set: { "grades.$.std" : 6 } }
)

我能够使用以下代码完成插入:

collection.update({ "operations": {$elemMatch: {_id:oid}}}, {$addToSet: { "operations.$.parameters" : parameter}}, function(err, result) {
        if (err) {
            res.send({'error':'An error has occurred'});
        } else {
            res.send(result[0]);
        }
});

以防万一有人需要它。