首页 > 解决方案 > 通过邮递员将 json 解析为猫鼬模式,但其格式无效

问题描述

const Item = mongoose.model('Item',new mongoose.Schema({
    title:{
        type:String,
        trim:true,
        required:true,
        minlength:1,
        maxlength:55

    },
    authorsIds:{
        type:[
            new mongoose.Schema({
            name:{
                type:String,
                required:true,
                minlength:3,
                maxlength:55
            }
        })]
    }

我正在尝试通过邮递员将值分配给 authorsIds "authorsIds":[{"name":"omer"} , {"name":"ali"}],但它不被接受,请以正确的方式帮助

标签: node.jsmongodbexpressmongoosepostman

解决方案


您应该保留两个不同的模式,其中项目模式具有作者的参考。

const Item = mongoose.model('Item',new mongoose.Schema({
    title:{
        type:String,
        trim:true,
        required:true,
        minlength:1,
        maxlength:55

    },
    authorsIds:[{
        type: Schema.Types.ObjectId,
        ref: "Author",
        required: true, //to make it compulsory
    }] // array of author ids , to only have single author remove []
}

const Author = mongoose.model('Author',new mongoose.Schema({
    name:{
        type:String,
        trim:true,
        required:true,
        minlength:3,
        maxlength:55
    }
}

之后在发布请求中,您可以先发送整个数据并创建作者,然后将这些 id 放入数组中并创建项目对象。


推荐阅读