因此,我尝试使用Mongoose检索多个文档,并使用HBS视图引擎呈现它们。不幸的是,我知道如何呈现视图的唯一方法是在用于从MongoDB数据库检索文档的res.render()
函数的回调中调用find()
。因此,我一次只能检索一个文档,我想知道如何将多个文档保存到变量中,然后使用res.render()
进行渲染。有人知道该怎么做吗?路由器代码如下。
基本上,我要从多个集合中提取数据,并想知道如何将find()
函数的输出保存为变量,然后将其传递给res.render()
函数进行渲染。您可以在下面看到我为将结果另存为变量而只返回承诺的尝试。
index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Schema = mongoose.Schema;
var moment = require('moment');
var supportForumListSchema = new Schema({
title: String,
description: String,
numPosts: Number,
dateCreated: Date
}, {collection: 'support-forum-listing'});
var artworkForumListSchema = new Schema({
title: String,
description: String,
numPosts: Number,
dateCreated: Date
}, {collection: 'artwork-forum-listing'});
var supportForumList = mongoose.model('supportForumList', supportForumListSchema);
var artworkForumList = mongoose.model('artworkForumList', artworkForumListSchema);
tempDate = new Date(1542325638042);
currentDate = new Date(1542333003752);
console.log("current date:" + currentDate.toDateString());
tempHoursAgo = currentDate - tempDate;
tempHoursAgo = tempHoursAgo / (1000*60*60);
tempDateString = tempHoursAgo.toFixed(0); // could use Number(string) to convert back to number
console.log(tempDateString + "hours ago");
// temp new posts array
var newPosts = [
{postTitle: "Need help!", numViews: 1, datePosted: tempDateString},
{postTitle: "Unknown identifier", numViews: 0, datePosted: tempDateString},
{postTitle: "Messing up my normals", numViews: 3, datePosted: tempDateString},
{postTitle: "Anyone able to help?", numViews: 3, datePosted: tempDateString}
];
/* GET home page. */
router.get('/', function(req, res, next) {
artworkDoc = artworkForumList.find().then(function(doc){
return doc;
});
console.log(artworkDoc);
supportForumList.find().then(function(supportDoc){
res.render('index', { title: 'Home - 3D Artists Forum', headerTitle: "3D Artist Forums", supportForumList: supportDoc , artworkForumList: artworkDoc, latestPosts: newPosts});
});
});
module.exports = router;
答案 0 :(得分:0)
请记住,请求是异步调用,因此您应该先进行链接才能获得所需的结果,否则“ supportForumList.find()”可能会在artworkForumList.find()之前响应
尝试这种方式
router.get('/', function(req, res, next) {
artworkDoc = artworkForumList.find().then(function(doc){
return doc;
}).then( doc => {
supportForumList.find().then(function(supportDoc){
res.render('index', { title: 'Home - 3D Artists Forum', headerTitle: "3D Artist Forums", supportForumList: supportDoc , artworkForumList: doc, latestPosts: newPosts});
});;
});
在这种方法中,仅当artworkForumList.find()已响应并且您在“ doc”变量中包含数据,然后将该数据作为参数传递时,才执行supportForumList.find()。
希望有帮助