Mongoose中如何忽略events引用为null的Registration文档?
Mongoose筛选排除events为null的Registration记录
要筛选掉events引用为null的Registration记录,只需在find()方法中添加对应查询条件,结合你现有populate逻辑,修改后的代码如下:
基础场景(events为单个引用字段)
如果events是单个ObjectId类型的引用,直接用$ne排除null值:
Registrations.find({ events: { $ne: null } }) .populate('events', { _id: '63ff4f974b030baef5025ce3' }) .populate('tags');
若你的Schema中events是可选字段,需要同时排除没有events字段的记录,可加上$exists条件:
Registrations.find({ events: { $exists: true, $ne: null } }) .populate('events', { _id: '63ff4f974b030baef5025ce3' }) .populate('tags');
扩展场景(events为数组类型引用)
如果events是关联多个Event的数组字段,除了排除null,还需要排除空数组:
Registrations.find({ $and: [ { events: { $ne: null } }, { events: { $not: { $size: 0 } } } ] }) .populate('events', { _id: '63ff4f974b030baef5025ce3' }) .populate('tags');
条件说明
$ne: null:直接排除events字段值为null的记录$exists: true:确保只返回包含events字段的记录$not: { $size: 0 }:排除events为空数组的情况(仅适用于数组类型的引用)
内容的提问来源于stack exchange,提问作者Muhammad Waqas
相关产品推荐
相关产品推荐

