Kelly Kelly - 6 months ago 11
Node.js Question

JSON element added not showing

I am using express.js to develop an API. I have a json object returned by mongoose and I need to add en element to each element in the result.docs.

I am doing this as follows:

for(a in result.docs)
{
result.docs[a].links={
"test":'test',
"test": 'test',
"test": 'test'
};

}


After doing so I am returning the result object, however the links are not added. On the other hand if I write

console.log(result.docs[1].links);


the object is shown properly.

Any ideas please?

Thanks

Answer

Possibly you're working with a mongoose Document instance instead of a plain object, in that case you could use the toObject method to get a plain object, so the implementation could be:

var objs = [];

for(var a in result.docs) {
   var obj = result.docs[a].toObject();
   obj.links = {
        "test":'test',
        "test": 'test', 
        "test": 'test' 
    };       
   objs.push(obj);
}

// Do something with objs

toObject Documentation