【问题标题】:Modifying the results of a Mongoose query修改 Mongoose 查询的结果
【发布时间】:2019-05-31 23:58:57
【问题描述】:

我正在处理MDN tutorial on ExpressJS with MongooseAsync,有一次我试图查询所有书籍,然后将其映射到其他查询以查找每本​​书的 BookInstance 数量。 (例如我想显示数据库中所有书籍的表格,然后列出我们有多少本)

// Display list of all books.
exports.book_list = function(req, res) {
  Book.find({}, 'title author')
    .exec(function(err, list){
      if (err) {return next(err);}

      async.map(list, function(book, next){
        BookInstance.countDocuments({book: book.id}, function(err, count){
          // Try and add the bookinstance count to the book object
          // use next(null, book);
        });
      }, function(err, modified_list){
        res.send(modified_list);
      });
    });
};

但是,以下没有任何作用:

book.count = count
next(null, book);

也没有:

book.set("count", count");
next(null, book);

在这两个示例中,项目都保持不变。但是,以下返回我所期望的:

var obj = {book: book, count: count};
next(null, obj);

Mongoose 的文档描述了 find() 返回文档,但我无法弄清楚为什么它们似乎是不可变的,或者 Document 实际上是什么。有没有办法让我只将 count 属性添加到原始返回的对象而不将其包装在另一个对象中?

【问题讨论】:

  • 接下来您要在哪里以及如何打电话?你的中间件应该有 next 作为它的第三个参数

标签: node.js mongoose async.js


【解决方案1】:

如果模型中未定义属性,则 mongoose 不会直接允许您添加该属性。但是,您可以使用 document._doc 更改为文档添加新属性。

【讨论】:

  • 我明白了,我试图将 Document 视为一个普通的旧 javascript 对象,但我猜由于 Document 支持更新 MongoDB 实例,它限制了我可以用它做什么。如果我修改 ._doc,更改是否真正反映在 DB 中?
  • 不,它只会更改服务器端的文档实例。它不会修改数据库中的实际数据。
猜你喜欢
  • 1970-01-01
  • 2015-07-09
  • 1970-01-01
  • 1970-01-01
  • 2020-04-08
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多