You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何从Mongoose的Member与Property两个集合获取并展示数据?

Fixing Your Mongoose Dual Collection Query Issue

Hey there! Let's break down what's going wrong with your route code and how to fix it so you can get data from both the Member and Property collections correctly.

What's Wrong With the Original Code?

There are two key issues here:

  1. Unresolved Promise for Members Collection:
    You're calling Members.find({}) but not waiting for its promise to resolve. The code immediately moves to Property.find({}).exec(), which means only the Property query's result is being passed to your .then() callback. The Members query runs in the background, but its result is never captured.

  2. Incorrect .then() Callback Parameters:
    The .then() function only accepts a single argument for the resolved value of the promise. Your (props, member) syntax is invalid here—member will always be undefined because it's being treated as an error handler parameter (which you aren't using).

Corrected Solutions

Here are two clean ways to fix this, both of which properly handle parallel execution of your database queries (since they don't depend on each other, running them in parallel is more efficient):

Solution 1: Using Promise.all()

This method runs both promises at the same time and waits for both to complete before proceeding:

const Property = require('../models/propsSchema');
const Members = require('../models/userSchema');

router.get('/', (req, res, next) => {
  // Wrap both queries in Promise.all to run them in parallel
  Promise.all([
    Members.find({}).exec(),
    Property.find({}).exec()
  ])
  .then(([member, props]) => {
    // Destructure the array of results to get each collection's data
    console.log('Members data:', member);
    console.log('Properties data:', props);
    res.render('index', { member, props });
  })
  .catch(err => {
    // Don't forget error handling!
    console.error('Failed to fetch data:', err);
    next(err); // Pass the error to Express's error handler
  });
});

Solution 2: Using async/await (More Readable)

If you prefer a synchronous-looking syntax, async/await makes this code even cleaner:

const Property = require('../models/propsSchema');
const Members = require('../models/userSchema');

router.get('/', async (req, res, next) => {
  try {
    // Await both queries in parallel using Promise.all
    const [member, props] = await Promise.all([
      Members.find({}).exec(),
      Property.find({}).exec()
    ]);

    console.log('Members data:', member);
    console.log('Properties data:', props);
    res.render('index', { member, props });
  } catch (err) {
    console.error('Failed to fetch data:', err);
    next(err);
  }
});

Key Notes

  • Parallel vs Sequential: Using Promise.all() ensures both queries run at the same time. If you awaited them one after another (without Promise.all), they'd run sequentially, which is slower for independent queries.
  • Error Handling: Always include a .catch() (or try/catch for async/await) to handle database errors—this prevents your server from hanging or crashing if a query fails.

内容的提问来源于stack exchange,提问作者Brandy Garrison

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.26 10:38:29