【问题标题】:How can I store dynamic object array in mongodb using Mongoose?如何使用 Mongoose 在 mongodb 中存储动态对象数组?
【发布时间】:2019-05-29 11:31:49
【问题描述】:

我想将数据对象数组按以下格式存储到 mongodb 中。

'

certifications' = {
                                  'certification1' = { 'name': ' SQL Server'},
  'certification2' = { 'name': 'Angular'},
....
}

同样,我想将数据存储到 monogodb 字段数组中。

Certiftication3,certificates4 它是动态的,它来自客户端。

如何实现该功能请帮助我...

【问题讨论】:

  • 所以来自客户端的数据看起来像这样:[{"name": "google"}, {"name": "SQL Server"}]
  • 刚刚更新了代码sn-p,你可以看看...

标签: javascript node.js angular mongodb mongoose


【解决方案1】:

像这样制作一个猫鼬模型:

const certificationSchema = new Schema({
    name: {
        type: String,
        required: true,
        minlength: 3,
        maxlength: 255,
    }
});

module.exports = mongoose.model('certification', certificationSchema);

在 API 路由中:

// certification.js

const Certification = require('../models/Certification');

// req.body = [{"name": "google"}, {"name": "SQL Server"}]

router.post('/', (req, res, next) => {
        // Model.insertMany() inserts an array of documents into a MongoDB collection should all of them be validated
        Certification.insertMany(req.body)
        .then((certification) => {
            if (certification) {
                   res.json(certification);
            } else {
                return next(new Error('Insertion failed'));
            }
        }).catch((err) => {
            next(err['message']);
        })
});

【讨论】:

    猜你喜欢
    • 2016-05-27
    • 2016-05-21
    • 2021-07-26
    • 2022-12-20
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2015-08-22
    相关资源
    最近更新 更多