11

I am working on an express js application where I need to update a nested array. 1) Schema :

//Creating a mongoose schema
var userSchema = mongoose.Schema({
_id: {type: String, required:true},
name: String,
sensors: [{
    sensor_name: {type: String, required:true},
    measurements: [{time: String}]
}] });

2) Here is the code snippet and explanation is below:

router.route('/sensors_update/:_id/:sensor_name/')
.post(function (req, res) {
User.findOneAndUpdate({_id:req.body._id}, {$push: {"sensors" : 
{"sensor_name" : req.body.sensor_name , "measurements.0.time": req.body.time } } },
{new:true},function(err, newSensor) {
if (err)
res.send(err);
res.send(newSensor)
}); });

I am able to successfully update a value to the measurements array using the findOneAndUpdate with push technique but I'm failing when I try to add multiple measurements to the sensors array.

Here is current json I get if I get when I post a second measurement to the sensors array :

{
"_id": "Manasa",
"name": "Manasa Sub",
"__v": 0,
"sensors": [
{
  "sensor_name": "ras",
  "_id": "57da0a4bf3884d1fb2234c74",
  "measurements": [
    {
      "time": "8:00"
    }
  ]
},
{
  "sensor_name": "ras",
  "_id": "57da0a68f3884d1fb2234c75",
  "measurements": [
    {
      "time": "9:00"
    }
  ]
  }]} 

But the right format I want is posting multiple measurements with the sensors array like this :

enter image description here

Right JSON format would be :

 {
"_id" : "Manasa",
"name" : "Manasa Sub",
"sensors" : [ 
    {
        "sensor_name" : "ras",
        "_id" : ObjectId("57da0a4bf3884d1fb2234c74"),
        "measurements" : [ 
            {
                "time" : "8:00"
            }
        ],
        "measurements" : [ 
            {
                "time" : "9:00"
            }
        ]
    }],
"__v" : 0 }

Please suggest some ideas regarding this. Thanks in advance.

InquisitiveGirl
  • 667
  • 3
  • 12
  • 31
  • Maybe this [answer](http://stackoverflow.com/questions/23577123/update-nested-array-with-mongoose-mongodb?rq=1) can help you to find the way . – Tan Le Sep 16 '16 at 01:38
  • Thanks, but I'm able to update a single value, my issue is I'm failing while I try updating multiple measurement(array) values to the sensor array based on the sensor name. – InquisitiveGirl Sep 16 '16 at 01:54
  • As @Hayden suggested, better change your schema. Your current schema is practically invalid. Keys inside an object must be unique. Try an online JSON parser and you will notice the error. – Nidhin David Sep 16 '16 at 03:42

3 Answers3

19

You might want to rethink your data model. As it is currently, you cannot accomplish what you want. The sensors field refers to an array. In the ideal document format that you have provided, you have a single object inside that array. Then inside that object, you have two fields with the exact same key. In a JSON object, or mongo document in this context, you can't have duplicate keys within the same object.

It's not clear exactly what you're looking for here, but perhaps it would be best to go for something like this:

{
"_id" : "Manasa",
"name" : "Manasa Sub",
"sensors" : [ 
    {
    "sensor_name" : "ras",
    "_id" : ObjectId("57da0a4bf3884d1fb2234c74"),
    "measurements" : [ 
        {
            "time" : "8:00"
        },
        {
            "time" : "9:00"
        }
    ]
},
{
    // next sensor in the sensors array with similar format
    "_id": "",
    "name": "",
    "measurements": []
}],
}

If this is what you want, then you can try this:

User.findOneAndUpdate(
    {  _id:req.body._id "sensors.sensor_name": req.body.sensor_name },
    { $push: { "sensors.0.measurements": { "time": req.body.time } } }
);

And as a side note, if you're only ever going to store a single string in each object in the measurements array, you might want to just store the actual values instead of the whole object { time: "value" }. You might find the data easier to handle this way.

Hayden Braxton
  • 1,151
  • 9
  • 14
10

Instead of hardcoding the index of the array it is possible to use identifier and positional operator $.

Example:

    User.findOneAndUpdate(
        {  _id: "Manasa" },
        { $push: { "sensors.$[outer].measurements": { "time": req.body.time } } }
        { "arrayFilters:" [{"outer._id": ObjectId("57da0a4bf3884d1fb2234c74")}]
    );

You may notice than instead of getting a first element of the array I specified which element of the sensors array I would like to update by providing its ObjectId.

Note that arrayFilters are passed as the third argument to the update query as an option.

You could now make "outer._id" dynamic by passing the ObjectId of the sensor like so: {"outer._id": req.body.sensorId}

In general, with the use of identifier, you can get to even deeper nested array elements by following the same procedure and adding more filters.

If there was a third level nesting you could then do something like:

User.findOneAndUpdate(
    {  _id: "Manasa" },
    { $push: { "sensors.$[outer].measurements.$[inner].example": { "time": req.body.time } } }
    { "arrayFilters:" [{"outer._id": ObjectId("57da0a4bf3884d1fb2234c74"), {"inner._id": ObjectId("57da0a4bf3884d1fb2234c74"}}]
);

You can find more details here in the answer written by Neil Lunn.

Jakub A Suplicki
  • 4,586
  • 1
  • 23
  • 31
  • 1
    Thanks! Figuring out how to use those identifiers and positional operators was tricky, but your simple examples helped a lot – radihuq Jan 17 '20 at 14:00
2

refer ::: positional-all

--- conditions :: { other_conditions, 'array1.array2.field_to_be_checked': 'value' } --- updateData ::: { $push : { 'array1.$[].array2.$[].array3' : 'value_to_be_pushed' } }

Suvarna
  • 165
  • 1
  • 8