【问题标题】:parsing json through postman to mongoose schema but its format is not valid通过邮递员将 json 解析为猫鼬模式,但其格式无效
【发布时间】:2020-08-25 20:52:33
【问题描述】:
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"}] , 但它不被接受请以正确的方式帮助

【问题讨论】:

  • 请显示不起作用的代码。您正在更新 mongodb 文档吗?你在创造它吗?此外,您的 authorsIds 在它有一个数组之前有一个类型键..
  • iauthorsIds:{ type:[ new mongoose.Schema({ name:{ type:String, required:true, minlength:3, maxlength:55 } })]
  • 我只是通过邮递员创建 authorsIds 但它不起作用.. 我不知道如何为 authorsIds 赋值
  • 可以通过邮递员成功插入item,但是item不包含authorsIds对吧?或者如果你有authorsIds 字段,你根本不能插入?
  • item 包含 authorsIds 子文档...并且未插入 authorsIds 字段中的名称值,这就是问题

标签: node.js mongodb express mongoose postman


【解决方案1】:

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

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 放入数组中并创建项目对象。

【讨论】:

    猜你喜欢
    • 2017-07-08
    • 2020-03-26
    • 2019-01-23
    • 2018-06-11
    • 2012-12-26
    • 1970-01-01
    • 2016-08-05
    • 2016-11-29
    • 2018-12-23
    相关资源
    最近更新 更多