gpt4 book ai didi

javascript - 如何使用node.js在mongodb的嵌套数组中添加新对象?

转载 作者:太空宇宙 更新时间:2023-11-03 23:33:08 26 4
gpt4 key购买 nike

我在 mongoDB 中存储了以下数据库结构:

    "location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]

我的问题是:如何将一个新对象推送到一个名为 Mike 的学生(其 ID 为“B00123456”)的图像数组中,我知道我应该使用 mongoDB 的 update 和 set 方法。但我就是找不到实现这一目标的方法。我想要的结果是:

"location" : "Halifax",
"students" : [
{
"name": "Mike",
"ID": "B00123456",
"images": [
{
"image_url":"",
"image_id":""
},
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
},
{
"name": "Rinan",
"ID": "B00999999",
"images": [
{
"image_url":"",
"image_id":""
}
]
}
]

下面是我尝试使用 MongoDB 的更新和设置:

    // Connect and create a new doc
MongoClient.connect('mongodb://username:password@iad1- mongos0.objectrocket.com:someNode/db_name', functionb(err, db) {
if (err) {
console.dir(err);
console.log("error connected to mongodb");
} else {
var collection = db.collection('student_info_collection');
var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax" },
{ ID:student_id}
{ name: student_name},
{$push: {
{
"images": [
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
]
}
}
}, function(err,result){
if (err)
console.log("Something's wrong");
else
res.sendStatus(200);
}
);
}
});

有什么帮助吗?

最佳答案

update()功能是

 update(selector, document[, options][, callback])

第一个参数是selector,请尝试这个

    var student_name = req.body.name;
var student_id = req.body.ID;
collection.update(
{ location:"Halifax",
'students.ID': student_id,
'students.name': student_name},
{$push: { "students.$.images":
{
"image_url":"www.example.com",
"image_id":"uqxhqbxqx_1219"
}
}
}, function(err,result){

关于javascript - 如何使用node.js在mongodb的嵌套数组中添加新对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35823457/

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