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

Mongoose中文档与关联文档文本搜索实现及空结果问题解决

文档及关联文档的文本搜索解决方案问题

需求说明

需要实现可对文档本身或其关联文档进行文本搜索的功能。

数据结构与样本数据

Activity Type Schema

const ActivityTypeSchema = new mongoose.Schema({
  activity_name: {
    type: String
  }
})

Activity Schema

const ActivitySchema = new mongoose.Schema({
  activity_type: {
    type: mongoose.Schema.Types.ObjectId,
    ref: 'activity_type',
  },
  location: {
    type: String
  },
  start_time: {
    type: String
  },
  end_time: {
    type: String
  }
})

activity_type 集合数据

[
  {
    "_id": { "$oid": "633f10f3386b79ac054cffff" },
    "activity_name": "Pushing"
  },
  {
    "_id": { "$oid": "633f10f3386b79ac054ccccc" },
    "activity_name": "Gymming"
  }
]

activity 集合数据

[
  {
    "_id": { "$oid": "633db6c1715278070bc9b94c" },
    "activity_type": { "$oid": "633f10f3386b79ac054cffff" },
    "start_time": "09:00",
    "end_time": "12:00",
    "location": "Dubai"
  },
  {
    "_id": { "$oid": "633db6c1715278070bc9b896" },
    "activity_type": { "$oid": "633f10f3386b79ac054ccccc" },
    "start_time": "09:00",
    "end_time": "12:00",
    "location": "USA"
  }
]

问题:尝试的聚合查询返回空数组

以下代码执行后返回空数组[]:

let getActivities = await Activity.aggregate([
  {
    "$lookup": {
      "from": "activity_type",
      "localField": "activity_type",
      "foreignField": "_id",
      "as": "activity_type_docs"
    }
  },
  {
    "$unwind": "$activity_type_docs"
  },
  {
    "$match": {
      "activity_type_docs.activity_name": {
        "$regex": regex,
        "$options": "i"
      }
    }
  }
])

期望的搜索输出

按 activity_name(如Gymming)搜索的结果

[
  {
    _id: 633db6c1715278070bc9b94c,
    is_deleted: false,
    activity_type: { _id: 633f10f3386b79ac054cffff, activity_name: 'Gymming' },
    start_time: '09:00',
    end_time: '12:00',
    location: 'Dubai'
  }
]

按 location(如Dubai)搜索的结果

[
  {
    _id: 633db6c1715278070bc9b94c,
    is_deleted: false,
    activity_type: { _id: 633f10f3386b79ac054cffff, activity_name: 'Gymming' },
    start_time: '09:00',
    end_time: '12:00',
    location: 'Dubai'
  }
]

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.08.17 00:31:38