【发布时间】:2021-07-01 22:18:00
【问题描述】:
代码来自MDN tutorial,关于如何使用 Node.js 和 mongoose。这个想法是发出并行请求以获取不同模型中的文档数。我不明白传递给每个 async.parallel 的回调来自哪里,它在哪里定义以及它做了什么,对我来说这似乎是一个虚拟函数。你能帮我理解吗?代码如下:
var Book = require('../models/book');
var Author = require('../models/author');
var Genre = require('../models/genre');
var BookInstance = require('../models/bookinstance');
var async = require('async');
exports.index = function(req, res) {
async.parallel({
book_count: function(callback) {
Book.countDocuments({}, callback); // Pass an empty object as match condition to find all documents of this collection
},
book_instance_count: function(callback) {
BookInstance.countDocuments({}, callback);
},
book_instance_available_count: function(callback) {
BookInstance.countDocuments({status:'Available'}, callback);
},
author_count: function(callback) {
Author.countDocuments({}, callback);
},
genre_count: function(callback) {
Genre.countDocuments({}, callback);
}
}, function(err, results) {
res.render('index', { title: 'Local Library Home', error: err, data: results });
});
};
【问题讨论】: