我想按以下格式将数据对象数组存储到mongodb中。
'
certifications' = {
'certification1' = { 'name': ' SQL Server'},
'certification2' = { 'name': 'Angular'},
....
}
同样,我想将数据存储到monogodb字段数组中。
证书3,证书4是动态的,它来自客户端。
如何实现该功能,请帮助我...
答案 0 :(得分: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']);
})
});