Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Can't add a new property to an object returned by Mongoose query [duplicate]

I'm coding an API with Node.js, MongoDB and Express. I can't seem to add a new property to the location objects I'm iterating through.

I don't understand the issue with my code at all. loc is a plain object, it should work. Am I wrong?

// **********************************
// GET Locations
// **********************************
// Create endpoint /api/locations for GET

exports.getLocations = function(req, res) {

    // Use the Location model to find all locations
    // of a particular user

    Location.find({}, function(err, locations) {
        if (err)
            res.send(err);
        var counter = 0;
        var l = locations.length;

        //we create a closure to access the current location object
        var closure = function(location) {

             //we are returning the callback
             return function(err, user) {
                if (err)
                    res.send(err);
                counter++;
                console.log("The location object: \n"+location+"\n\n");

                console.log("The value we want to add to the object: \n"+user.username+"\n\n");

                //THAT DOESN'T WORK
                location.username = user.username;

                console.log("The updated object: \n"+location+"\n\n");

                if(counter === l) res.json(locations);
            };
        };

        //We respond with the locations
        for (var i = 0; i < l; i++) {

            //we call our function
            User.findById(locations[i].userId, "username", closure(locations[i]));
        }
    });
};

Here's the output I get in the console... This is so weird.

The location object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }


The value we want to add to the object:
test123


The updated object:
{ _id: 54c65c665ff13962b6a367a1,
  userId: '54c659ba8ac00324b617f3f9',
  message: 'Big party here tonight!!',
  longitude: 45.5,
  latitude: 73.5667,
  __v: 0 }
like image 907
Felix D. Avatar asked Jan 26 '15 19:01

Felix D.


1 Answers

In our case you have MongooseDocument not plain JS object. In order to get plain JS object you should use .lean like this

Location.find({}).lean().exec(function(err, locations) {
    ...
});
like image 64
Oleksandr T. Avatar answered Oct 23 '22 14:10

Oleksandr T.