You need to enable JavaScript to run this app. 如何在Mongoose嵌套数组中按指定条件查询对应userId
优惠活动
大模型
产品
解决方案
定价
更多

如何在Mongoose嵌套数组中按指定条件查询对应userId

问题排查点

  • 参数拼写错误:函数定义的形参为publiserId(缺失字母h),查询条件中引用的是publisherId,二者不匹配导致查询时publisherId实际为undefined,无法匹配到对应数据。
  • 数组查询语法错误:查询条件中"books.$.bookId"写法错误,$占位符仅用于更新操作、结果投影场景下定位匹配的数组下标,查询数组内子字段匹配值时,直接写"books.bookId"即可。
  • 冗余Promise包装:Mongoose的findOne方法本身返回Promise实例,手动封装一层属于不必要操作,还可能增加异常捕获的逻辑漏洞。

修正后代码

const allTheRelatedData = (publisherId, bookId) => {
  return myBookSchema
    .findOne(
      // 查询条件
      {
        publisherId: publisherId,
        "books.bookId": bookId
      },
      // 投影配置:仅返回userId和匹配到的books元素,不需要返回全量books数组
      { userId: 1, "books.$": 1 }
    )
    .then(data => {
      console.log(data);
      // 如果需要直接返回userId,可直接 return data?.userId
      return data;
    })
    .catch(error => {
      console.log(error);
      throw error;
    });
};

如果需要获取匹配的book条目内的userId,直接取返回结果中books[0].userId即可;如果是文档顶层的userId,直接取data.userId即可。

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.14 11:24:01