gpt4 book ai didi

javascript - 使用动态键推送到 mongodb 数组

转载 作者:可可西里 更新时间:2023-11-01 10:30:00 25 4
gpt4 key购买 nike

我正在尝试通过动态 key 推送数据

数据库结构:

{
"obj1":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":123;
},
{
"obj2":{
"array":[
{
"field1":"text1"
},
{
"field2":"text2"
}
]
},
"id":1234;
}

我正在尝试使用变量作为映射路径中的键:

var a = 'obj2';
db.collection('fooCollection').update({'id':1234},{$push:{a.array:{ "field3":"text3"}}});

如果我这样做:

db.collection('fooCollection').update({'id':1234},{$push:{"obj2.array":{ "field3":"text3"}}});

它有效,但我非常需要使用动态 key 。

最佳答案

对象字面量无法做到这一点。试试这个:

var a = 'obj2';

var pushObj = {};
pushObj[a + '.array'] = { "field3": "text3" };

db.collection('fooCollection').update({ 'id':1234 }, { $push: pushObj });

关于javascript - 使用动态键推送到 mongodb 数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/27513504/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com