5

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' }
Community
  • 1
  • 1
Risto Novik
  • 8,199
  • 9
  • 50
  • 66
  • I don't know about it returning a function, but your 'index' is not doing what you want. You shouldn't loop over arrays using `for..in`. Use a proper `for` loop with a range. Also `findById` is asynchronous and you are never capturing the index is a new scope, so you are always going to be using the very last index when setting name. – loganfsmyth Feb 10 '12 at 16:36
  • yes this true, what would be best way to solve the last problem ? – Risto Novik Feb 10 '12 at 22:06
  • 1
    You'd need to capture array index in a new scope. Usually you'd wrap the contents of the for look with `(function(index) { ... })(index);`. That creates and immediately executes a new function, so the value of index inside the function is captured in a closure with the findOne callback. – loganfsmyth Feb 11 '12 at 01:39

1 Answers1

10

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.

Brian Antonelli
  • 736
  • 9
  • 16
  • Thank you! It took me hours to find this! Now that I know what I was looking for, here's a link to the API docs: http://mongoosejs.com/docs/api.html#document_Document-toObject – Pascal Aug 21 '13 at 11:49