Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Modifying mongoose object literal result does not work [duplicate]

Possible Duplicate:
Why can’t you modify the data returned by a Mongoose Query (ex: findById)

First I am making the query to mongoDB, get all the correct results but only the small modification to object literal does not work. What I am trying to do, is adding new field to comments. I tried to use the DBref method but it didn't work so i make 2 queries now.

var query = Rss.findOne({ _id: itemId});
query.exec(function(err, feed) {
  if (!err && feed.comments) {
    console.log(feed.comments.length);
    for (var index in feed.comments) {
      var author = feed.comments[index].author;
      if (author !== undefined) {
        User.findById(author, function(err, user) {

          /**Problem is here **/
          feed.comments[index].name = 'Some random field';
          console.log('Added new field' + util.inspect(feed));

        });
      }

    }
  }
});

Also the response is this without the missing .name field.

Added new field{ _id: 4f34f343c7b0434217000012,
  original_link: 'http://com',
  publish_date: Fri, 10 Feb 2012 10:36:00 GMT,
  summary: 'some text',
  title: 'title exampel',
  comments: 
   [ { body: 'well',
       author: 4f30265e6f60dc061d000002,
       _id: 4f34f3b6f96c58541700000f,
       create_date: Fri, 10 Feb 2012 10:38:46 GMT } ],
  create_date: Fri, 10 Feb 2012 10:36:51 GMT }

// EDIT more information

Well i haven't found the answer but some how the console.log(feed.comments[index]) returns reference to function. Maybe someone who has more experience with mongoosejs could explain what would be workaround in this situation.

{ [Function] author: 'Some random field' }
like image 430
Risto Novik Avatar asked Feb 10 '12 10:02

Risto Novik


1 Answers

You have to tell Mongoose to convert the result into a proper object. Before modifying the feed object simply call:

feed = feed.toObject();

And then you can add all the additional properties you want to it.

like image 56
Brian Antonelli Avatar answered Nov 02 '22 09:11

Brian Antonelli