1

I want to store data object array into mongodb as below format.

'

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

Like wise I want to store data into monogodb field array.

Certiftication3, certifications4 it is dynamic it comes from client side.

How to acheive that functionality please help me...

2
  • so will the data coming from the client side look like this: [{"name": "google"}, {"name": "SQL Server"}] Commented Jan 2, 2019 at 20:46
  • Just updated code snippet can u pls look into it... Commented Jan 2, 2019 at 20:50

1 Answer 1

1

Make a mongoose model like so:

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

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

in API route:

// 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']);
        })
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.