簡體   English   中英

嵌套 Mongoose 相同類型的模式

[英]Nested Mongoose Schema of same type

我必須創建一個 mongoose 模式。 例如,我有一個名為“類別”的集合,其中存儲了父類別。 並且一個父類別可以有多個子類別。

因此,父類別和子類別的類別結構是相同的。

請幫助任何人如何為此結構創建架構。 示例響應如下:

{
"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",
    },
]
}

這是我完成類似任務的代碼。

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.'
            })
        })
})

這是相關的模式結構

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')

希望對您有所幫助!

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM