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

Mongoose嵌套$and/$or查询报Unexpected token '}'语法错误如何解决

问题根因

1. 语法错误原因

原查询条件中$or的数组结构不符合语法规范:

  • $or接收条件对象组成的数组,原写法中第二个配对条件没有放在$or的数组范围内,且存在多余的闭合括号,导致解析时识别到多余的}抛出语法错误
  • 存在结构嵌套错误,内层条件的括号匹配混乱

2. 业务逻辑对齐提醒

你提供的SQL语句中筛选条件为matchcompleted = 'yes',但原代码中写的是MatchCompleted: {$eq: undefined},二者逻辑完全相反,修改时请按需调整。

正确的查询代码
matchRecord = await MatchRegister.findOne({
  $and: [
    {
      $or: [
        // 配对条件1:i为选手1、j为选手2
        {
          $and: [
            { Player1Name: slot1SaturdayArray[i] },
            { Player2Name: slot1SaturdayArray[j] }
          ]
        },
        // 配对条件2:j为选手1、i为选手2
        {
          $and: [
            { Player1Name: slot1SaturdayArray[j] },
            { Player2Name: slot1SaturdayArray[i] }
          ]
        }
      ]
    },
    { TournamentName: activeTournamentRecord.TournamentName },
    // 如需对齐SQL逻辑,此处改为 { MatchCompleted: 'yes' }
    { MatchCompleted: {$eq: undefined} }
  ]
}).exec()
精简优化写法

MongoDB默认同一对象内的多个字段为且关系,无需显式写内层$and,代码可简化为:

matchRecord = await MatchRegister.findOne({
  TournamentName: activeTournamentRecord.TournamentName,
  // 如需对齐SQL逻辑,此处改为 MatchCompleted: 'yes'
  MatchCompleted: undefined,
  $or: [
    { Player1Name: slot1SaturdayArray[i], Player2Name: slot1SaturdayArray[j] },
    { Player1Name: slot1SaturdayArray[j], Player2Name: slot1SaturdayArray[i] }
  ]
}).exec()

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

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.10.06 10:48:03