尝试检查mongoose updateOne中的条件时发生强制转换错误

chhkpiq4  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(81)

我试图使用updateOne在我的文档中设置一个名为isFullCapacity的字段,并使用以下代码将upsert设置为true-

var temp = await Slot.updateOne(
          { branch: branchId, timeSlot: timeSlot, date: dates[i] },
          {     
            $addToSet: {
              timeRecords: createdTimeRecords[i],
          
            },
             $set: {
               isFullCapacity: {
                $cond: {
                  if: {
                    $gte: [
                      { $size: { $ifNull: ["$classRecords", []] } },
                      timeSlot.maxStudents,
                    ],
                  },
       then: true,
                  else: false,
                },
              },
            },
          },
          },

          { upsert: true }
        );

字符串
在这段代码中,我试图将一个Slot文档的isFullCapacity字段设置为true,如果timeRecords数组的长度(它是Slot文档中的objectIds字段数组)等于timeSlot.maxCustomers值。timeSlot是我通过req.body获得的一个结构化对象,它也包含maxCustomers属性。
当我运行这段代码时,它显示这个错误-

"name": "CastError",
            "message": "Cast to boolean failed for value \"{ '$cond': { if: { '$gte': [Array] } } }\" (type Object) at path \"undefined\""
        },
        "name": "CastError",
        "message": "Cast to Boolean failed for value \"{ '$cond': { if: { '$gte': [Array] } } }\" (type Object) at path \"isFullCapacity\" because of \"CastError\""


我试着检查timeRecords是否为null,这是chatgpt建议的,但问题仍然存在-

{ $size: { $ifNull: ["$timeRecords", []] } },


这是Schema-

const Slot = Schema({
  date: {
    type: Date,
    index: { order: 1 },
  },
  isFullCapacity: {
    type: Boolean,
    default: false,
  },
  timeSlot: {
    type: Schema.Types.Mixed,
  },
  branch: {
    type: Schema.Types.ObjectId,
    ref: "Branch",
    required: true,
  },

  timeRecords: {
    type: [
      {
        type: mongoose.Schema.Types.ObjectId,
        ref: "timeRecords",
      },
    ],
  },
});

module.exports = mongoose.model("Slot", Slot);


概括一下要求,如果Slot文档的timeRecords.length等于timeSlot.maxCustomers,则Slot文档的isFullCapacity字段应设置为true

aelbi1ox

aelbi1ox1#

您是否也可以发布模式,以便更好地了解您的问题,例如您期望的确切数据类型
CastError通常意味着你输入的值不是mognoose期望的类型,例如如果id:a3ndtn6和你给予mongoose id: an3ntn6$
这里的specialCase字符不是mongoose期望的类型。所以mongoose默认会抛出错误代码为11000的错误

相关问题