[英]Nested Mongoose Schema of same type
I have to create a mongoose schema.我必须创建一个 mongoose 模式。 For example, I have a collection named "categories" in which parent categories are stored.
例如,我有一个名为“类别”的集合,其中存储了父类别。 And a parent category can have multiple sub-categories.
并且一个父类别可以有多个子类别。
So the category structure is the same for the parent and child category.因此,父类别和子类别的类别结构是相同的。
Please help anyone how to create schema for this structure.请帮助任何人如何为此结构创建架构。 A sample response is below:
示例响应如下:
{
"id": "category_id_123"
"name": "General",
"parent_id": null,
"childs": [
{
"id": "category_id_124",
"name": "General Knowledge",
"parent_id": "category_id_123",
},
{
"id": "category_id_125",
"name": "Math",
"parent_id": "category_id_123",
},
]
}
This is the code that I accomplish similar task.这是我完成类似任务的代码。
router.put('/addchild', (req, res, next) => {
Parent.findById(
req.headers.uid // Id of the parent
)
.then((parent) => {
return parent.updateOne({
$addToSet: {
child: req.body
}
}).then(() => {
res.status(200).send({
message: 'child added'
})
})
}).catch(() => {
res.status(500).send({
message: 'child adding error.'
})
})
})
Here is relevant schema structure这是相关的模式结构
const mongoose = require('mongoose')
const Schema = mongoose.Schema
const parentSchema = new Schema({
_id: {
type: mongoose.Schema.Types.ObjectId,
createIndex: true,
required: true,
auto: true
},
email: {
type: String,
required: true,
unique: true,
match: /[a-z0-9!#$%&'*+/=?^_`{|}~-]+(?:\.[a-z0-9!#$%&'*+/=?^_`{|}~-]+)*@(?:[a-z0-9](?:[a-z0-9-]*[a-z0-9])?\.)+[a-z0-9](?:[a-z0-9-]*[a-z0-9])?/
},
child: [],
})
module.exports = mongoose.model('Parent', userSchema, 'parent')
Hope it will help you!希望对您有所帮助!
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.