如何在猫鼬中设置引用文档_id可选?

时间:2019-11-26 20:52:45

标签: node.js mongodb mongoose

我在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}},那么我的服务器就不会给出这样的错误?

1 个答案:

答案 0 :(得分:0)

在猫鼬中,通常每个字段都是可选的,除非您指定required:true

此错误:

  

在路径“品牌”处,对值“”的对象ID投放失败

似乎您正在尝试发送brand:''作为输入,这意味着您实际上在文档中具有品牌字段,因此您得到MongooseError,您需要具有验证功能在这里,如果您确实需要在某些文档中使用空字符串,或者可以在将其发送到db操作之前从输入对象中删除品牌字段(当它不等于ObjectId()时)。