我试图使用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
。
1条答案
按热度按时间aelbi1ox1#
您是否也可以发布模式,以便更好地了解您的问题,例如您期望的确切数据类型
CastError
通常意味着你输入的值不是mognoose期望的类型,例如如果id:a3ndtn6
和你给予mongoose id: an3ntn6$
这里的specialCase字符不是mongoose期望的类型。所以mongoose默认会抛出错误代码为
11000
的错误