![](/img/trans.png)
[英]How to get data from multiple collections in mongodb using mongoose?
[英]How to retrieve multiple collections using Mongoose
因此,我尝试使用Mongoose检索多个文档,并使用HBS视图引擎呈现它们。 Unfortunatley,我知道如何渲染视图的唯一方法是在用于从MongoDB数据库中检索文档的find()
函数的回调中调用res.render()
。 因此,我一次只能检索一个文档,并且我想知道如何将多个文档保存到变量中,然后使用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;
请记住,请求是异步调用,因此您应该先进行链接才能获得所需的结果,否则“ 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()。
希望能帮助到你
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.