提问者:小点点

同类型嵌套猫鼬模式


我得创建一个猫鼬模式。 例如,我有一个名为“categories”的集合,父类别存储在其中。 一个父类别可以有多个子类别。

因此类别结构对于父类别和子类别是相同的。

请帮助任何人如何创建此结构的架构。 响应示例如下:

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

共1个答案

匿名用户

这是我完成类似任务的代码。

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

希望对你有帮助!