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