MongoDB中执行populate后如何查询字段?附代码示例
Let me break down how you can work with the fields in your populated results, based on the code and sample response you shared:
First, recap your current code and returned data
Your query:
schemeProductDetailsModel.find({}) .populate({ path: 'schemeProduct', model: schemeProductsMd }) .populate({ path: 'qrCode', model: qrcodesMd, match : {code : "TB00006"} }) .exec();
Sample returned result:
[ { "note": "ghi chú", "_id": "5adecfc654c19a0014f55032", "schemeProduct": { "quantityDeployed": 0, "quantityRemaining": 10, "_id": "5a7d089efeb222491ae36f9a", "product": "5a7bbf5bfeb222491acd2b54", "quantityDeploy": 10, "updatedAt": "2018-03-08T03:29:13.379Z" }, "qrCode": { "_id": "5a7a..." } } ]
1. Access fields directly from the returned results
Once you've fetched the data with .exec(), you can access any field (including nested populated fields) using standard object property notation. Remember the result is an array of documents, so target specific elements first.
Here's a practical example in your callback:
schemeProductDetailsModel.find({}) .populate({ path: 'schemeProduct', model: schemeProductsMd }) .populate({ path: 'qrCode', model: qrcodesMd, match : {code : "TB00006"} }) .exec((err, docs) => { if (err) { console.error('Query error:', err); return; } if (docs.length === 0) { console.log('No documents found'); return; } // Grab the first document from the results const firstDoc = docs[0]; // Access top-level fields console.log('Note:', firstDoc.note); console.log('Document ID:', firstDoc._id); // Access nested fields from the populated schemeProduct console.log('Remaining quantity:', firstDoc.schemeProduct.quantityRemaining); console.log('Last updated:', firstDoc.schemeProduct.updatedAt); // Access fields from the populated qrCode (add? to avoid errors if qrCode is null) console.log('QR Code ID:', firstDoc.qrCode?._id); });
2. Specify which fields to return during populate (optimize data transfer)
If you don't need all fields from the populated collections, use the select option in your populate configuration to only fetch the fields you care about. This reduces data transfer and keeps results cleaner.
For example:
schemeProductDetailsModel.find({}) .populate({ path: 'schemeProduct', model: schemeProductsMd, select: 'quantityRemaining updatedAt' // Only return these two fields (_id is included by default) }) .populate({ path: 'qrCode', model: qrcodesMd, match : {code : "TB00006"}, select: '_id -__v' // Return _id and exclude the __v version field }) .exec();
- To exclude a field, prefix it with
-(e.g.,-updatedAtto exclude the timestamp) - To exclude the default
_id, add-_idto your select string.
3. Filter fields from the main document
You can also limit which fields are returned from the main schemeProductDetailsModel collection using .select() right after .find():
schemeProductDetailsModel.find({}) .select('note -_id') // Only return the note field, exclude _id .populate({ path: 'schemeProduct', model: schemeProductsMd }) .populate({ path: 'qrCode', model: qrcodesMd, match : {code : "TB00006"} }) .exec();
内容的提问来源于stack exchange,提问作者IT_WRU

