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

Mongoose查询返回空数组但NoSQLBooster同查询正常如何解决?

问题原因及修复方案

核心错误点

1. 字段名拼写不匹配

你的Schema中定义的兴趣字段是interests(末尾带s),但前端传入的查询参数中字段名写为interest(末尾无s),MongoDB会将其识别为不存在的字段,直接导致无匹配结果。

2. 查询值类型不匹配

前端传入的所有ID都是字符串格式,而MongoDB中存储的是ObjectId类型。你代码中使用的JSON.parse(JSON.stringify(this.req.body.filterParam))会丢失所有类型信息,导致Mongoose的自动类型转换失效,无法匹配到存储的ObjectId值。

3. 查询条件缺失

你当前的代码逻辑仅在无过滤参数时才会添加isDeleted: false条件,有过滤参数时不会默认携带该条件,和NoSQLBooster中执行的查询条件不一致。


修复代码示例

const mongoose = require('mongoose');
const ObjectId = mongoose.Types.ObjectId;

makeQuery = { isDeleted: false }; // 统一默认携带未删除条件
if (this.req.body?.filterParam && !_.isEmpty(this.req.body.filterParam)) {
  const filterParam = _.cloneDeep(this.req.body.filterParam); // 用lodash深拷贝替代序列化反序列化,避免丢失类型
  // 对所有ObjectId类型字段的$in数组做显式类型转换
  const objectIdFields = ['skills', 'interests', 'university', 'title'];
  objectIdFields.forEach(field => {
    if (filterParam[field]?.$in && Array.isArray(filterParam[field].$in)) {
      filterParam[field].$in = filterParam[field].$in.map(id => ObjectId(id.trim()));
    }
  });
  Object.assign(makeQuery, filterParam);
}

// 后续的find逻辑保持不变即可
let getListOfUsers = await Users.find(makeQuery)
// 剩余原有代码...

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.04 06:09:03