【问题标题】:Mongoose: Add data to returned result setMongoose:将数据添加到返回的结果集中
【发布时间】:2015-02-08 12:45:53
【问题描述】:

在 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

转换结果也不起作用,因为我不断收到“[...] has no method 'xy'”错误。

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

我还漏掉了什么?

【问题讨论】:

  • 你想用你的数据做什么?您是否尝试通过向其添加 thumbnail 字段来修补每个作者?
  • 是的,这是我的意图。因此,我需要遍历结果(上面的示例中缺少循环代码)并将更改应用于作者的每个数据集。

标签: json mongodb mongoose


【解决方案1】:

一旦您使用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);
});

【讨论】:

  • 好的,成功了。感谢到目前为止。但是假设我想保留原始的 Mongoose 格式,我该如何操作返回的查询数据(设置会导致如前所述的错误)?
  • lean() 是我一直在寻找的。​​span>
【解决方案2】:

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

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

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

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2010-10-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-26
    • 1970-01-01
    相关资源
    最近更新 更多