如何查询未被指定学生申请的Event集合数据?
获取未被指定学生申请的活动数据
实现思路
- 第一步:从
Apply_event集合中查询当前学生已申请的所有活动ID,整理成ID数组 - 第二步:以该ID数组为排除条件,查询
Events集合,返回符合要求的活动数组
基础版代码实现
可以新增一个接口来获取未申请的活动,示例代码如下:
// 引入Events模型(确保路径正确) const Events = require('../models/Events'); route.get('/student_unapplied_events', async (req, res) => { try { // 获取当前登录学生的ObjectId const studentId = mongoose.Types.ObjectId(req.session.student_id); // 查询该学生已申请的所有活动ID const appliedRecords = await Apply_event.find( { applicant: studentId }, { events_applied: 1, _id: 0 } ).lean(); // 提取活动ID数组,无申请记录时设为空数组 const excludedEventIds = appliedRecords.map(item => item.events_applied) || []; // 查询所有未被该学生申请的活动 const unappliedEvents = await Events.find({ _id: { $nin: excludedEventIds } }).lean(); // 返回结果数组 res.json(unappliedEvents); } catch (error) { console.error('查询未申请活动出错:', error); res.status(500).json({ message: '查询失败' }); } });
高效聚合查询方案
如果想减少数据库查询次数,可以用MongoDB聚合管道一步完成:
route.get('/student_unapplied_events', async (req, res) => { try { const studentId = mongoose.Types.ObjectId(req.session.student_id); const unappliedEvents = await Events.aggregate([ { // 左连接Apply_event集合,匹配当前学生的申请记录 $lookup: { from: 'apply_events', localField: '_id', foreignField: 'events_applied', let: { targetStudent: studentId }, pipeline: [ { $match: { $expr: { $eq: ['$applicant', '$$targetStudent'] } } } ], as: 'application' } }, { // 筛选出无申请记录的活动(application数组为空) $match: { application: { $size: 0 } } }, { // 移除冗余的application字段 $project: { application: 0 } } ]); res.json(unappliedEvents); } catch (error) { console.error('查询未申请活动出错:', error); res.status(500).json({ message: '查询失败' }); } });
注意事项
- 确保
Events模型已正确引入到当前路由文件中 - 如果
req.session.student_id本身就是ObjectId类型,可省略mongoose.Types.ObjectId()转换 - 当学生无任何申请记录时,
$nin空数组会返回所有活动,符合业务预期
内容的提问来源于stack exchange,提问作者Anagha A S
相关产品推荐
相关产品推荐

