我正在使用我的节点应用程序返回一个Mongo集合(使用Mongoose),并且当它返回时为每个集合项增加一个新值时尝试遍历它。
我正在使用下划线,但由于某种原因,它不会附加我正在添加到列表中的内容。我做错了什么?
我的代码:
Submission.find({}).sort('date', -1).execFind(function (err, submissions) {
_.each(submissions, function (submission, key) {
submissions[key]['newValue'] = 'test';
});
});
但它没有添加newValue:'test'。
当我调试它时,我得到了这个:
[{
user_id: 1234,
title: 'testing tyhe slug generation',
description: '',
topic: 'movies',
source: 'http://www.apple.com',
ip: '127.0.0.1',
approved: false,
slug: 'testing-tyhe slug generation',
_id: 5133a60e16661e41db000001,
created: Sun Mar 03 2013 11:35:42 GMT-0800 (PST),
thumbnail: '9146edb190a960c1cc3b0eda7d9f719d'
}, {
user_id: 1234,
title: 'New submission test slug',
description: '',
topic: 'food-drink',
source: 'http://www.apple.com',
ip: '127.0.0.1',
approved: false,
slug: 'new-submission-test-slug',
_id: 5133a6c8adcde860db000001,
created: Sun Mar 03 2013 11:38:48 GMT-0800 (PST),
thumbnail: 'd80003cf9c81a4982fbb81c99abb52dc'
}]
这是一个异步问题吗?
答案 0 :(得分:0)
@bob_cobb,Mongoose将结果作为“文档”的集合返回。我的意思是一组javascript对象而不是JSON。因此,在这些文档中完成的任何粗心操作也会影响数据库内容。
根据我的理解,您希望在文档中添加动态或添加的属性。所以做如下,
Submission.find({}).sort('date', -1).execFind(function (err, submissions) {
_.each(submissions, function (submission, key) {
//Here you are converting javascript object into JSON.
//That is remove all the functions associated with "submission" object.
submissions[key] = submissions[key].toJSON();
submissions[key]['newValue'] = 'test';
//Note: Here submission.save() won't work.
});
});