如何从Mongoose的Member与Property两个集合获取并展示数据?
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:
Unresolved Promise for Members Collection:
You're callingMembers.find({})but not waiting for its promise to resolve. The code immediately moves toProperty.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.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—memberwill always beundefinedbecause 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 (withoutPromise.all), they'd run sequentially, which is slower for independent queries. - Error Handling: Always include a
.catch()(ortry/catchfor async/await) to handle database errors—this prevents your server from hanging or crashing if a query fails.
内容的提问来源于stack exchange,提问作者Brandy Garrison

