我在node.js服务器中有这样的产品schema
export var Product = mongoose.model(
"product",
new Schema({
name: String,
brand: { type: Schema.Types.ObjectId, ref: "brand" },
colors: [String],
sizes: [String],
description: String,
thumnbail: String,
images: [String],
thumnbnailImage: String,
price: Number,
quantity: Number,
discount: Number,
category: { type: Schema.Types.ObjectId, ref: "category" },
createdAt: String,
updatedAt: String,
isActive: { type: Boolean, default: true }
})
);
在此schema
中,我引用了brand
集合。但是,用户不必从客户端提供brand
来添加product
。现在,当我尝试添加product
时,我没有给出brand
的{{1}},因为它是可选的,所以_id
会抛出这样的错误
node.js
我该如何在product validation failed: brand: Cast to ObjectID failed for value "" at path "brand"
文档中为品牌创建_id
,并在字段中填写一个可选字段,以便如果用户不提供product
的{{1}},那么我的服务器就不会给出这样的错误?
答案 0 :(得分:0)
在猫鼬中,通常每个字段都是可选的,除非您指定required:true
。
此错误:
在路径“品牌”处,对值“”的对象ID投放失败
似乎您正在尝试发送brand:''
作为输入,这意味着您实际上在文档中具有品牌字段,因此您得到MongooseError
,您需要具有验证功能在这里,如果您确实需要在某些文档中使用空字符串,或者可以在将其发送到db操作之前从输入对象中删除品牌字段(当它不等于ObjectId()
时)。