0

I need to handle POST request, after which some info should be added to multiple docs, but $push doesn't seem to work - it pushes an empty object, $set on the other hand works great. I've tried for loop, Q and now async, but something still doesn't work.

Schema:

var MeasurementSchema = new Schema({
  _id: false,
  t: Number,
  v: Number
});

var SensorSchema = new Schema({
  _id: { type: String, required: true },
  unit: String,
  measurements: [ MeasurementSchema ]
});

POST request:

{
    "timestamp": 100000,
    "measurements": [
        ["1/1/1", 10, "temperature"],
        ["1/1/2", 20, "sunny"],
        ["1/1/3", 30, "foo"],
        ["1/1/4", 110, "bar"]
    ]
}

POST handling:

 .post(function(req, res) {
    var r = req.body;
    var i = 0;

    async.whilst(
        function() { return i < r.measurements.length; },
        function(callback) {
            Sensor.findByIdAndUpdate(
                r.measurements[i][0],
                {
                    $push: { measurements: { t: r.timestamp, v: r.measurements[i][1] } },
                    $set: { unit: r.measurements[i][2] }
                },
                { upsert: true, new: true, safe: true },
                function (err, result) {
                    if(err) console.log(err);
                    i++;
                    callback(err,result);
                }
            ); 
        },
        function(err) {
            if(err) console.log(err);
        }

    );
})
Rafal
  • 1
  • 2
  • Possible duplicate of [JavaScript closure inside loops – simple practical example](http://stackoverflow.com/questions/750486/javascript-closure-inside-loops-simple-practical-example) – Scimonster Dec 18 '16 at 12:39
  • Can you comment your error output. – Mathankumar K Dec 18 '16 at 13:07
  • @MathankumarK I don't recieve any errors - in database I've got this: ``` { "_id" : "1/1/1", "__v" : 0, "measurements" : [ { } ], "unit" : "temperature" } ``` – Rafal Dec 18 '16 at 13:41

1 Answers1

0

You are doing a simple mistake in the $push query.

measurement is an array of objects with fields t and v , currently you are trying to push t and v individually, but not as a single object, just enclose them in {}, and it should work fine.

Replace :

$push: { measurements: { t: r.timestamp, v: r.measurements[i][1] } },

with :

$push: { measurements: { { t: r.timestamp, v: r.measurements[i][1] } } },

hope this helps you.

Ravi Shankar Bharti
  • 8,922
  • 5
  • 28
  • 52