[英]Mongoose, express- create schema with array of objects
I try to create mongoose schema containing array of objects.我尝试创建包含对象数组的猫鼬模式。 Schema looks like:架构看起来像:
const mapSchema = new Schema({
name: {
type: String
},
description: {
type: String
},
rate: {
type: Number,
default: 0
},
sumOfRates: {
type: Number,
default: 0
},
places: [
{
name: String,
description: String,
difficulty: { type: String, default: 0 },
sumOfRates: { type: String, default: 0 },
lat: Number,
lng: Number
}
]
}, {
timestamps: true
})
Places is array of objects. Places 是对象数组。 I tried to create mongoose schema and use it as element of places array(places: [ref: 'placeSchema']).我尝试创建猫鼬模式并将其用作场所数组的元素(场所:[ref:'placeSchema'])。
const placeSchema = new Schema({
name: {
type: String
},
description: {
type: String
},
difficulty: {
type: Number,
default: 0
},
lat: {
type: Number
},
lng: {
type: Number
}
})
But I think it would create another, separeted document in mongo(places document).但我认为它会在 mongo(places document) 中创建另一个单独的文档。 Does it?是吗? I try to avoid such situation To keep it in one document.Now(code pasted above), gives me an error, when i try to insert json in postman:我尽量避免这种情况为了将它保存在一个文档中。现在(上面粘贴的代码),当我尝试在邮递员中插入 json 时,给了我一个错误:
{
"name": "ergergergg",
"description": "rgergrg",
"places": [
{
"name":"cvcv",
"description":"rgergrg",
"lat":233,
"lng":232
}]
}
Error:错误:
ValidationError: places: Cast to Array failed for value "[object Object]" at path "places"
Why such error?为什么会出现这样的错误? How to fix this?如何解决这个问题?
The appropriate way to go would be to use of a sub schema.合适的方法是使用子模式。
const subSchema = new Schema({
name: {
type: String,
},
description: {
type: String,
},
difficulty: {
type: Number,
default: 0,
},
lat: {
type: Number,
},
lng: {
type: Number,
},
});
const mapSchema = new Schema({
name: {
type: String,
},
description: {
type: String,
},
rate: {
type: Number,
default: 0,
},
sumOfRates: {
type: Number,
default: 0,
},
places: [subSchema],
}, {
timestamps: true
});
To insert a new data插入新数据
mapSchema.insert({
name: "ergergergg",
description: "rgergrg",
places: [
{
name: "cvcv",
description": "rgergrg",
lat: 233,
lng: 232,
},
],
});
To make the subSchema optional, you can maybe do something like this @DanMossa :要使 subSchema 可选,您可以执行以下操作 @DanMossa :
pages: {
type: [subSchema],
required: false
},
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.