我已经在mongodb中创建了一个项目Crud操作,在更新操作中一切正常,我需要更新数组中的对象,因为每个ID都有不同的解决方案
猫鼬模式
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const educationSchema = new Schema({
qualification:{ type:String, required:false},
passedyear:{ type:String, required:false},
course:{ type:String, required:false}
})
const freelancerSchema = new Schema({
name:{type:String},
education:[educationSchema],
skill:{type:Array,required:true},
},
{
timestamps:true,
});
const freelancer = mongoose.model('freelancer',freelancerSchema);
module.exports=freelancer;
控制器在下面
const Freelancer = require('../../models/freelancer');
exports.updatefreelancer=function (req, res) {
const id = req.params.id;
const updateObject = req.body;
Freelancer.updateOne({ _id:id }, { $set:updateObject })
.exec()
.then(() => {
res.status(200).json({
message: 'freelancer is updated',
updatenew: updateObject,
});
})
.catch((err) => {
res.status(500).json({
message: 'Server error'
});
});
}
在下面的代码中,我需要更新教育内的对象
mongodb数据
"skill": [
],
"_id": "5e68ee62e87207270c484c7d",
"name": "fdfdf",
"education": [
{
"_id": "5e6b8b3884edde05089385cd",
"qualification": "UG",
"passedyear": "2020",
"course": "BE"
},
{
"_id": "5e6b8b3884edde05089385ce",
"qualification": "PG",
"passedyear": "2021",
"course": "me"
}