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

Mongoose如何从嵌套对象中查询数据 获取用户关联的所有项目

你之前的写法存在两个核心问题:

  1. 查询语法错误:直接写currentlyWorkingEmployees: { _id: userId }的匹配逻辑是要求currentlyWorkingEmployees数组完全等于你传入的对象,而不是匹配数组内任意一项的_id符合要求。
  2. 类型不匹配:req.user.userId通常为字符串类型,而Mongoose自动生成的_id为ObjectId类型,类型不一致会导致匹配失败。

最简实现方案(普通find查询即可满足需求)

const mongoose = require('mongoose');
const getMyProjects = async (req, res) => {
  // 先把字符串格式的用户ID转为ObjectId类型,Mongoose6+版本可省略该步但建议保留避免环境差异
  const userId = new mongoose.Types.ObjectId(req.user.userId);
  // 用点语法匹配内嵌数组字段
  const projects = await Project.find({
    "currentlyWorkingEmployees._id": userId
  });
  res.json({projects});
};

如果你需要使用聚合查询,正确写法如下

const mongoose = require('mongoose');
const getMyProjects = async (req, res) => {
  const userId = new mongoose.Types.ObjectId(req.user.userId);
  const projects = await Project.aggregate([
    {
      $match: {
        "currentlyWorkingEmployees._id": userId
      }
    }
  ]);
  res.json({projects});
};

扩展说明

如果你需要同时查询用户作为创建者的项目和作为参与成员的项目,可以调整查询条件:

const projects = await Project.find({
  $or: [
    { "currentlyWorkingEmployees._id": userId },
    { createdBy: userId }
  ]
});

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.24 10:24:03