Reputation: 51
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...
Upvotes: 1
Views: 765
Reputation: 480
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']);
})
});
Upvotes: 1