【发布时间】:2012-03-02 20:35:47
【问题描述】:
可能重复:
Why can’t you modify the data returned by a Mongoose Query (ex: findById)
首先我对 mongoDB 进行查询,得到所有正确的结果,但只有对对象文字的小修改不起作用。我想要做的是向 cmets 添加新字段。我尝试使用 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));
});
}
}
}
});
响应也是这样,没有缺少 .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 }
// 编辑更多信息
嗯,我还没有找到答案,但是一些 console.log(feed.cmets[index]) 如何返回对函数的引用。也许对 mongoosejs 有更多经验的人可以解释在这种情况下有什么解决方法。
{ [Function] author: 'Some random field' }
【问题讨论】:
-
我不知道它返回一个函数,但你的“索引”没有做你想做的事。您不应该使用
for..in循环数组。使用适当的for循环和范围。findById也是异步的,你永远不会捕获索引是一个新的范围,所以在设置名称时你总是会使用最后一个索引。 -
是的,这是真的,解决最后一个问题的最佳方法是什么?
-
您需要在新范围内捕获数组索引。通常你会用
(function(index) { ... })(index);包装for 查找的内容。这会创建并立即执行一个新函数,因此函数内 index 的值会在带有 findOne 回调的闭包中捕获。
标签: javascript node.js mongoose