You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何用Mongoose查询未加入也未被邀请加入指定项目的用户?

Mongoose 实现查询既未被邀请也不是项目成员的用户

实现逻辑

需要匹配同时满足两个条件的用户:

  • invitations 数组中不包含目标项目ID(未被邀请)
  • projects 数组中不包含目标项目ID(不是项目成员)

代码实现

方法1:使用$nin查询

直接通过$nin运算符指定数组不包含目标值即可:

// 替换为你的目标项目ID,如果存储的是ObjectId类型请先转换
const targetProjectId = 'c'; 
const eligibleUsers = await UserModel.find({
  invitations: { $nin: [targetProjectId] },
  projects: { $nin: [targetProjectId] }
});

方法2:使用$nor查询

$nor运算符会匹配所有列出条件都不成立的文档,写法更简洁:

const targetProjectId = 'c';
const eligibleUsers = await UserModel.find({
  $nor: [
    { invitations: targetProjectId },
    { projects: targetProjectId }
  ]
});

注意事项

  • 如果invitations和projects数组存储的是Mongoose的ObjectId类型而非字符串,查询前需要先把目标项目ID转为ObjectId,避免类型不匹配查询失败:
    const targetProjectId = mongoose.Types.ObjectId('项目ID字符串');
    
  • 可根据业务需要链式调用.select()、.limit()、.skip()等方法自定义返回字段、分页规则。

内容的提问来源于stack exchange,提问作者thomasaar

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.10.06 20:15:03