Manoj Sanjeewa
Manoj Sanjeewa

Reputation: 1069

Node js adding new property to a array of objects when returning from mongoose collection

I am creating app using nodejs, express, mongoose. And mongodb.user is the mongoose schema model and I am trying to fetch user array of objects, that query is perfect and my problem is I want to add new property for each user. I have tried as follows. But it does not add to the collection.

exports.memberlist = function(req, res) {
        user.find({}).exec(function(err, collection) {
             collection.forEach(function(member){
             member.city  = 'Colombo';
             collection.push(member);
             });
        res.send(collection);
        });
};

Upvotes: 0

Views: 1413

Answers (2)

Adil Aourchane
Adil Aourchane

Reputation: 384

By default, Mongoose doesn't allow to add a property to an object extracted from MongoDB DB. To do so, you have two alternatives :

1/ before exec statement you add a lean() method : 
user.find({}).lean().exec(function(err, collection) {do whatever you want with collection}

2/ collection = collection.toObject();

Upvotes: 0

HDK
HDK

Reputation: 814

you can do like this

in Schema level create create virtual property

userSchema.virtual('city').get(function () {
  return 'Colombo';
});

in controller level

exports.memberlist = function(req, res,next)
{
  user.find({}).exec(function(err, users)
    {
if(!err)
{
res.json(200, users.toObject({virtual: true}));
}
else
{
next(err);
}

    });
};

Upvotes: 1

Related Questions