MongoDB / Mongoose:如何将元素推送到嵌套对象中的数组?
MongoDB / Mongoose: How to push element to an array in a nested object?
我正在使用 mongoose 创建一个 mongodb 数据库,我根据以下模式在其中存储数据:
const Incidents_Schema = ({
assetID: Number,
dataHora: {
year: Number,
month: Number,
day: Number,
hour: Number
},
data:
{
1: [ {supman: String, desc: String, ticketID: Number} ],
2: [ {supman: String, desc: String, ticketID: Number} ],
3: [ {supman: String, desc: String, ticketID: Number} ],
4: [ {supman: String, desc: String, ticketID: Number} ],
5: [ {supman: String, desc: String, ticketID: Number} ],
}
});
const evento = mongoose.model("Incident", Incidents_Schema);
我成功地向数组“1”添加了一个属于对象 "data" 的元素。所以,现在我已经存储了以下条目:
{
"_id" : ObjectId("5e7df900c79032556c5d4ad1"),
"assetID" : 1100006971,
"dataHora" : { "year" : 2020, "month" : 3, "day" : 26, "hour" : 21 },
"data" : { "1" : [ { "_id" : "5e7df900c79032556c5d4ad2", "supman" : "foo1", "desc" : "foo2", "ticketID" : 123} ],
"2" : [ ],
"3" : [ ],
"4" : [ ],
"5" : [ ]
}
}
这是我的问题: 我想将另一个元素推入数组“1”。我在 google 上做了一些搜索并尝试了几种方法,但其中 none 确实有效。
我试过的最后一个是:
evento.update({"_id": "5e7df900c79032556c5d4ad1"}, {"$push": {"data.$.1": {supman: "foo3", desc: "foo4", ticketID: 456}}});
我是否错误地构建了查询或架构本身?
谢谢。
好的,所以我找到了一个方法:
evento.updateOne({"_id": "5e7df900c79032556c5d4ad1"}, {"$push": {"data.1": {supman: "foo3", desc: "foo4", ticketID: 456}}}, {upsert:true}, function(err){
if(err){
console.log(err);
}else{
console.log("Successfully added");
}
});
还是谢谢你!
我正在使用 mongoose 创建一个 mongodb 数据库,我根据以下模式在其中存储数据:
const Incidents_Schema = ({
assetID: Number,
dataHora: {
year: Number,
month: Number,
day: Number,
hour: Number
},
data:
{
1: [ {supman: String, desc: String, ticketID: Number} ],
2: [ {supman: String, desc: String, ticketID: Number} ],
3: [ {supman: String, desc: String, ticketID: Number} ],
4: [ {supman: String, desc: String, ticketID: Number} ],
5: [ {supman: String, desc: String, ticketID: Number} ],
}
});
const evento = mongoose.model("Incident", Incidents_Schema);
我成功地向数组“1”添加了一个属于对象 "data" 的元素。所以,现在我已经存储了以下条目:
{
"_id" : ObjectId("5e7df900c79032556c5d4ad1"),
"assetID" : 1100006971,
"dataHora" : { "year" : 2020, "month" : 3, "day" : 26, "hour" : 21 },
"data" : { "1" : [ { "_id" : "5e7df900c79032556c5d4ad2", "supman" : "foo1", "desc" : "foo2", "ticketID" : 123} ],
"2" : [ ],
"3" : [ ],
"4" : [ ],
"5" : [ ]
}
}
这是我的问题: 我想将另一个元素推入数组“1”。我在 google 上做了一些搜索并尝试了几种方法,但其中 none 确实有效。 我试过的最后一个是:
evento.update({"_id": "5e7df900c79032556c5d4ad1"}, {"$push": {"data.$.1": {supman: "foo3", desc: "foo4", ticketID: 456}}});
我是否错误地构建了查询或架构本身?
谢谢。
好的,所以我找到了一个方法:
evento.updateOne({"_id": "5e7df900c79032556c5d4ad1"}, {"$push": {"data.1": {supman: "foo3", desc: "foo4", ticketID: 456}}}, {upsert:true}, function(err){
if(err){
console.log(err);
}else{
console.log("Successfully added");
}
});
还是谢谢你!