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

Mongoose查询聊天记录返回空数组,请求技术排查

问题排查:查询聊天记录返回空数组

核心问题

你当前的查询条件采用了嵌套对象精确匹配的方式,而MongoDB中{members:{userId:id}}这种写法会要求整个members对象完全等于{userId:id}——但你的members结构同时包含userId和postOwner两个字段,所以这种查询永远无法匹配到实际存在的文档。

修复代码

将查询条件改为使用点符号访问嵌套字段,直接匹配members下的单个属性:

export async function GET(req,{params}){
  let {ids} = params
  const id = ids[0]
  console.log(id)
  await connectDB()
  // 用点符号指定嵌套字段
  const chat = await Chat.find({
    $or: [
      {"members.userId": id},
      {"members.postOwner": id}
    ]
  })
  console.log(chat)
  // 注意:find方法始终返回数组,需通过长度判断是否有数据
  if(chat.length > 0){
    return NextResponse.json({message:'chat found',chat})
  }else{
    return NextResponse.json({message:'no chat found'})
  }
}

额外检查项

  • 确认id的值和数据库中存储的userId/postOwner字符串完全一致(包括大小写、空格等细节)
  • 直接在MongoDB客户端(如Compass)执行db.chats.find({$or: [{"members.userId": "你的测试ID"}, {"members.postOwner": "你的测试ID"}]}),验证数据库中是否存在目标文档

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.06.28 14:57:27