相同类型的嵌套猫鼬模式

时间:2020-06-11 13:29:11

标签: javascript node.js mongodb mongoose

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

因此,父类别和子类别的类别结构相同。

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

    JSONObject json = Util.parseJson(httpRequest);
    logger.debug("Response data", json.toString());

1 个答案:

答案 0 :(得分: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')

希望它会对您有所帮助!