我创建了两个函数,它们从mongodb获取值然后我想将这些函数呈现给视图但是我一次只能分配函数但是不能同时分配两个函数来在视图中渲染。 我想知道执行以下操作的最佳技巧。 实际上我想通过以下网址显示该类别的书籍
http://localhost:3000/category/catid/56696ddeef90d5400b604361
这将获取所提及类别的所有书籍以及侧栏中的所有书籍类别。
我的代码正在关注
function get_books_details(callback){
//console.log(get_cat_id);
//res.render('pages/category', { title: 'Express','get_cat':get_cat_id});
var get_books=[];
var array = [];
/* query mongodb start */
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
db.collection('book', function(err, collection) {
collection.find().toArray(function(err,results) {
results.forEach(function(item) {
array.push(item);
});
callback(array);
// console.log(array);
});
});
} //else end
});
/* query mongodb end */
}
function get_cat_details(callback){
//console.log(get_cat_id);
//res.render('pages/category', { title: 'Express','get_cat':get_cat_id});
var get_cats_call=[];
var array_cats = [];
/* query mongodb start */
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
db.collection('category', function(err, collection) {
collection.find().toArray(function(err,results) {
results.forEach(function(itemcats) {
array_cats.push(itemcats);
});
callback(array_cats);
//console.log(array_cats);
});
});
} //else end
});
/* query mongodb end */
}
router.get('/catid/:catId', function(req, res) {
var get_cat_id=req.params.catId;
get_books_details(function(data_book){
console.log(data_book);
res.render('pages/category', {title:"LNA Publication","allbuk":data_book,"get_category":get_cat_id});
});
get_cat_details(function(data_cat){
console.log(data_cat);
res.render('pages/category', {title:"LNA Publication",itm:data_cat,"get_category":get_cat_id});
});
});
CLI输出控制台的屏幕截图 Screenshot of command line interface
答案 0 :(得分:2)
你可以试试这个:
router.get('/catid/:catId', function(req, res) {
var get_cat_id=req.params.catId;
get_books_details(function(data_book){
console.log(data_book);
get_cat_details(function(data_cat){
console.log(data_cat);
res.render('pages/category', {title:"LNA Publication",itm:data_cat,"allbuk":data_book,"get_category":get_cat_id});
});
});
});