DoxyTweak
DoxyTweak

Reputation: 25

MongoDB / Mongoose: How to push element to an array in a nested object?

I'm using mongoose to create a mongodb database where I'm storing data according to the following schema:

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);

I successfully added an element to array "1", that belongs to object "data". So, now I have stored the following entry:

{ 
  "_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" : [ ] 
            }
}

Here is my question: I want to push another element to array "1". I did some search on google and tried several ways but none of them did work. The last one I tried was:

evento.update({"_id": "5e7df900c79032556c5d4ad1"}, {"$push": {"data.$.1": {supman: "foo3", desc: "foo4", ticketID: 456}}});

Did I structured the query or the Schema itself incorrectly?

Thank you.

Upvotes: 0

Views: 36

Answers (1)

DoxyTweak
DoxyTweak

Reputation: 25

Ok, so I found a way by doing:

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");
}

});

Thank you anyway!

Upvotes: 1

Related Questions