首页 > 解决方案 > 如何使用 Mongoose 检索多个集合

问题描述

所以我正在尝试使用 Mongoose 检索多个文档并使用 HBS 视图引擎呈现它们。不幸的是,我知道如何呈现视图的唯一方法是res.render()在回调内部调用find()用于从 MongoDB 数据库检索文档的函数。因此,我一次只能检索一个文档,我想知道如何将多个文档保存到变量中,然后使用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;

标签: javascriptnode.jsexpressmongoose

解决方案


请记住,请求是异步调用,因此您应该链接 then 以获得所需的结果,否则“supportForumList.find()”可能会在 artifactForumList.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});
    });;
      

});

在这种方法中,supportForumList.find() 仅在 artifactForumList.find() 响应并且您在“doc”变量中有数据时才执行,然后将该数据作为参数传递。

希望能帮助到你


推荐阅读