我有一个像这样的MongoDB对象:
[
{ 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 }
]
我如何为每个嵌套数组添加一个额外的元素,所以它会是这样的:
[
{ 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 },
]
我尝试了这个,但它不起作用:
for(var i=0; i<JSONobject.length; i++){
JSONobject[i].newName= NewValue;
}
我正在使用node.js,该对象是我从mongodb查询得到的结果。
这是功能:
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);
});
}
修改
经过一番研究后,我发现返回的Mongoose Document不是JSON对象,所以我现在正尝试将其转换为对象。
答案 0 :(得分:1)
我找到了答案!!
我们需要告诉Mongoose我们需要的是在查询链中使用results
返回的lean()
的纯JavaScript版本。
那样Mongoose会跳过创建完整模型实例的步骤,我们直接得到results
我们可以修改
像这样:
exports.Posts = function(UserID, PostID, callback) {
Post.find( { post: PostID } , function(err, results) {
for (var i=0; i<results.length; i++){
results[i].newName = "NewValue";
}
console.log(results);
return callback(null, results);
}).lean();
}
答案 1 :(得分:0)
我不确定为什么for
循环会在这里失败,因为它对我来说似乎很好。但试试这个:
results = results.map(function(item) {
item.newName = "NewValue";
return item;
});
这将创建一个新数组,其中每个原始项都附加新值。
(根据经验,使用.forEach()
,.map()
,.filter()
,.reduce()
,.every()
和.some()
几乎总是优越的在循环数组时到for