dimanche 8 mars 2015

How to add an extra element in every nested array of a MongoDB object?

I have a MongoDB object like this:



[
{ poster_ip: '127.0.0.1',
post_body: 'example',
_id: 54fc1f7808bac08f6d25f24b,
__v: 0 },

{ poster_ip: '127.0.0.1',
post_body: 'example',
_id: 54fc1f7808bac08f6d25f24a,
__v: 0 }
]


how can i add an extra element to every nested array so it would be like this:



[
{ poster_ip: '127.0.0.1',
post_body: 'example',
_id: 54fc1f7808bac08f6d25f24a,
__v: 0,
newName: NewValue },

{ poster_ip: '127.0.0.1',
post_body: 'example',
_id: 54fc1f7808bac08f6d25f24b,
__v: 0,
newName: NewValue },
]


I tried this but it didn't work:



for(var i=0; i<JSONobject.length; i++){
JSONobject[i].newName= NewValue;
}


I'm using node.js, the object is the result i get from a mongodb query.


Here is the function:



exports.Posts = function(UserID, PostID, callback) {

Post.find( { post: PostID } , function(err, results) {

var r = results.toObject(); //here i get error 'has no method toObject'

for (var i=0; i<r.length; i++){
r[i].newName = "NewValue";
}

console.log(r);
//i don't see any changes here with console.log

return callback(null, results);
});
}


EDIT:


After a little more research i found out that the returned Mongoose Document isn't a JSON object, so i'm trying now to convert it to an object.


Aucun commentaire:

Enregistrer un commentaire