修改mongoose对象文字结果不起作用

Ris*_*vik 5 javascript mongoose node.js

可能重复:
为什么不能修改Mongoose Query返回的数据(例如:findById)

首先,我正在对mongoDB进行查询,得到所有正确的结果,但只对对象文字的小修改不起作用.我想做的是为评论添加新字段.我尝试使用DBref方法,但它没有工作,所以我现在进行2次查询.

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));

        });
      }

    }
  }
});
Run Code Online (Sandbox Code Playgroud)

响应是没有缺少.name字段的响应.

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 }
Run Code Online (Sandbox Code Playgroud)

//编辑更多信息

好吧,我还没有找到答案,但一些如何console.log(feed.comments [index])返回函数的引用.也许对mongoosejs有更多经验的人可以解释在这种情况下会有什么解决办法.

{ [Function] author: 'Some random field' }
Run Code Online (Sandbox Code Playgroud)

Bri*_*lli 11

你必须告诉Mongoose将结果转换为适当的对象.在修改feed对象之前,只需调用:

feed = feed.toObject();
Run Code Online (Sandbox Code Playgroud)

然后,您可以添加所需的所有其他属性.


归档时间:

查看次数:

2867 次

最近记录:

12 年,12 月 前