如何使用Mongoose查询同一文档中三个嵌套数组内的字段?
解决方案:查询ProfileSchema中嵌套数组的相关字段
首先先明确你的Schema结构:ProfileSchema里的list字段包含三个嵌套数组acceptedList、requestedList、pendingList,每个数组项都是Schema1的结构(带id(引用UserinfoSchema)、name、from字段)。下面分几种常见场景给出查询语句:
1. 查询所有Profile文档,返回三个列表的全部字段
如果需要返回这三个嵌套数组的所有内容,直接用find()即可,默认会返回所有字段(除了_id可以通过投影控制):
// 查询所有Profile文档,包含list下的三个数组 Profile.find({}) .then(profiles => { console.log(profiles); }) .catch(err => { console.error(err); });
2. 只返回指定的嵌套字段(按需投影)
如果不需要返回所有字段,比如只想获取每个列表里的name和from,可以用MongoDB的**投影(projection)**来精准控制返回内容:
// 只返回profilename和list下三个数组的name、from字段 Profile.find({}, { profilename: 1, 'list.acceptedList.name': 1, 'list.acceptedList.from': 1, 'list.requestedList.name': 1, 'list.requestedList.from': 1, 'list.pendingList.name': 1, 'list.pendingList.from': 1, _id: 0 // 可选:排除默认返回的_id字段 }) .then(profiles => { console.log(profiles); }) .catch(err => { console.error(err); });
注:投影里
1表示包含该字段,0表示排除。如果只指定包含的字段,其他默认会被排除(除了_id,需要手动设置_id: 0来排除)。
3. 关联查询引用的UserinfoSchema数据
因为Schema1里的id是ref: 'UserinfoSchema'的引用字段,如果你需要把这个id对应的Userinfo文档数据一起返回,可以用Mongoose的populate()方法:
// 查询并关联填充三个数组里id对应的Userinfo数据 Profile.find({}) .populate({ path: 'list.acceptedList.id list.requestedList.id list.pendingList.id', model: 'UserinfoSchema' // 这里要和你定义UserinfoSchema时的model名称一致 }) .then(profiles => { console.log(profiles); }) .catch(err => { console.error(err); });
这样返回的每个数组项里的id字段会被替换成对应的Userinfo文档的完整数据,而不是单纯的ObjectId。
4. 结合投影和关联查询
如果既要控制返回字段,又要填充关联数据,可以把投影和populate结合起来:
Profile.find({}, { profilename: 1 }) .populate({ path: 'list.acceptedList.id', model: 'UserinfoSchema', select: 'username email' // 只填充Userinfo里的username和email字段 }) .then(profiles => { console.log(profiles); }) .catch(err => { console.error(err); });
内容的提问来源于stack exchange,提问作者code.mevn
相关产品推荐
相关产品推荐

