node.js - 通过邮递员将 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"}]
,但它不被接受,请以正确的方式帮助
解决方案
您应该保留两个不同的模式,其中项目模式具有作者的参考。
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 放入数组中并创建项目对象。
推荐阅读
- java - “在以下位置找不到存储库:”为 Eclipse 安装 TestNG 插件时出错
- python - 用于更新 pyqt5 gui 的 Python 多处理
- hadoop - 如何使用 Airflow 运行 HDFS Copy 命令?
- python-3.x - 如何使用 psycopg2 指定列名
- assembly - 汇编代码的预处理不起作用(#if #else #endif)
- android - 如何在 kotlin 中使用自定义 camera2 开关闪光灯
- spring - Swagger中基于路径参数的多请求模型| 春天
- node.js - 如何从后端快速服务器获取数据到前端反应应用程序,反之亦然
- python - Flask TypeError:视图函数没有返回有效响应。该函数要么返回 None 要么在没有 return 语句的情况下结束
- insomnia - linux mint 19.2 Failed to fetch Insomnia Repository