修改 Mongoose 查询的结果
Modifying the results of a Mongoose query
我正在研究 MDN tutorial on ExpressJS with Mongoose and Async,有一次我试图查询所有书籍,然后将其映射到其他查询以查找每本书的 BookInstances 数量。 (例如我想显示数据库中所有书籍的 table,然后列出我们有多少本)
// 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);
在这两个示例中,项目都保持未修改状态。但是,以下 returns 我期望的是:
var obj = {book: book, count: count};
next(null, obj);
Mongoose 的文档描述了 find() returns 文档,但我无法弄清楚为什么它们看起来是 immutable,或者 Document 实际上是什么。有没有办法让我只向原始返回的对象添加 count
属性 而不是将其包装在另一个对象中?
如果模型中未定义 属性,则 mongoose 不会直接允许您添加 属性。但是,您可以使用 document._doc 更改向文档添加新属性。
我正在研究 MDN tutorial on ExpressJS with Mongoose and Async,有一次我试图查询所有书籍,然后将其映射到其他查询以查找每本书的 BookInstances 数量。 (例如我想显示数据库中所有书籍的 table,然后列出我们有多少本)
// 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);
在这两个示例中,项目都保持未修改状态。但是,以下 returns 我期望的是:
var obj = {book: book, count: count};
next(null, obj);
Mongoose 的文档描述了 find() returns 文档,但我无法弄清楚为什么它们看起来是 immutable,或者 Document 实际上是什么。有没有办法让我只向原始返回的对象添加 count
属性 而不是将其包装在另一个对象中?
如果模型中未定义 属性,则 mongoose 不会直接允许您添加 属性。但是,您可以使用 document._doc 更改向文档添加新属性。