Как я могу сохранить массив динамических объектов в mongodb, используя Mongoose? - PullRequest
0 голосов
/ 02 января 2019

Я хочу сохранить массив объектов данных в mongodb, как показано ниже.

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

Как и я, я хочу сохранить данные в массиве поля monogodb.

Сертификация3, сертификация4, она динамична, со стороны клиента.

Как получить эту функциональность, пожалуйста, помогите мне ...

1 Ответ

0 голосов
/ 02 января 2019

Сделайте мангуст модель так:

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']);
        })
});
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...