Mongoose:将数据添加到返回的结果集

时间:2014-12-10 10:46:11

标签: json mongodb mongoose

在MEAN环境中使用mongoose,我需要将数据添加到返回的mongoose查询结果中。查询返回作者列表。我想在查询结果中向每个作者添加缩略图字段(=缩略图图像的计算路径)。这是我的代码(出于简单原因缺少循环代码):

var searchQuery = Author.find({ ...foo... }); 
searchQuery.limit(10);
//...

searchQuery.exec(function (err, authors) {
   authors.set('thumbnail', 'test'); //causes error, no effect
   res.json(authors);
});

我知道mongoose不返回普通的JS / JSON对象,因此我需要先将结果集转换为能够操作它。事实上,对我来说什么都没有用,我几乎尝试了一切:

searchQuery.lean().exec(function (err, authors) { //lean() option makes no difference

转换结果也不起作用,因为我不断得到" [...]没有方法' xy'"错误。

var tempresult = authors.toObject(); //--> causes error above
var tempresult = authors.toJSON(); //--> causes error above

我还能错过什么?

2 个答案:

答案 0 :(得分:9)

使用lean()将生成的文档转换为纯JS对象后,他们不会像set那样拥有任何可用的Mongoose模型实例方法,因此您需要直接使用普通的JavaScript对象技术操作它们:

searchQuery.lean().exec(function (err, authors) {
   authors = authors.map(function(author) {
       author.thumbnail = 'test';
       return author;
   });
   res.json(authors);
});

如果您想将结果维护为mongoose文档,则需要将{strict: false}作为第三个参数传递给set,以允许添加任意字段:

searchQuery.exec(function (err, authors) {
   authors = authors.map(function(author) {
       author.set('thumbnail', 'test', {strict: false});
       return author;
   });
   res.json(authors);
});

答案 1 :(得分:0)

你也可以在函数中获取返回的文档(res,doc ...) 并做:

var docForMap = JSON.parse(JSON.stringify(doc));

这将为您提供一个可以使用的新副本。

相关问题