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

Igo*_* P. 3 json mongoose mongodb

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

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

searchQuery.lean().exec(function (err, authors) { //lean() option makes no difference
Run Code Online (Sandbox Code Playgroud)

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

var tempresult = authors.toObject(); //--> causes error above
var tempresult = authors.toJSON(); //--> causes error above
Run Code Online (Sandbox Code Playgroud)

我还能错过什么?

Joh*_*yHK 12

一旦你通过使用将生成的文档转换为普通的JS对象lean(),它们就不会有任何可用的Mongoose模型实例方法set,所以你需要使用普通的JavaScript对象技术直接操作它们:

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

如果要将结果保存为mongoose docs,则需要传递{strict: false}第三个参数set以允许添加任意字段:

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