Javascript 如何在不删除其余对象的情况下使用对象ID更新对象数组?
如何在不删除其余对象的情况下使用对象ID更新对象数组?这是我的模式:Javascript 如何在不删除其余对象的情况下使用对象ID更新对象数组?,javascript,mongodb,express,mongoose,Javascript,Mongodb,Express,Mongoose,如何在不删除其余对象的情况下使用对象ID更新对象数组?这是我的模式: const mongoose = require('mongoose'); const Schema = mongoose.Schema; const ProfileSchema = new Schema({ user: { type: Schema.Types.ObjectId, ref: 'user' }, company: { type: Str
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const ProfileSchema = new Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
company: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
type: [String],
required: true
},
experience: [{
jobTitle: {
type: String,
required: true
},
company: {
type: String,
required: true
},
workLocation: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
workResponsibilities: {
type: String,
required: true
}
}],
date: {
type: Date,
default: Date.now
}
})
module.exports = Profile = mongoose.model('profile', ProfileSchema)
这是我的密码:
//PUT request
router.put(
"/experience/:exp_id",
[auth,
[
check("jobTitle", "Job title is required").not().isEmpty(),
check("company", "Company Name is required").not().isEmpty(),
check("workLocation", "Work Location is required").not().isEmpty(),
check("from", "Start date is required").not().isEmpty(),
check("workResponsibilities", "Work responsibilitites is required").not().isEmpty()
],
],
async (req, res) => {
const errors = validationResult(req);
if (!errors.isEmpty()) {
return res.status(400).json({
errors: errors.array(),
});
}
const {
jobTitle,
company,
workLocation,
from,
to,
current,
workResponsibilities
} = req.body;
//Build profile object
const profileFields = {};
profileFields.user = req.user.id;
profileFields.experience_id = req.params.exp_id
//Build social object
profileFields.experience = {};
if (jobTitle) profileFields.experience.jobTitle = jobTitle;
if (company) profileFields.experience.company = company;
if (workLocation) profileFields.experience.workLocation = workLocation;
if (from) profileFields.experience.from = from;
if (to) profileFields.experience.to = to;
if (current) profileFields.experience.current = current;
if (workResponsibilities) profileFields.experience.workResponsibilities = workResponsibilities;
try {
let profile = await Profile.findOne({
user: req.user.id,
});
if (profile) {
const updateIndex = profile.experience.map(item => item)
//Update Profile
profile = await Profile.findOneAndUpdate({
user: req.user.id,
}, {
$set: profileFields,
}, {
new: true,
});
return res.json(profile);
}
} catch (err) {
console.error(err.message);
res.status(500).send("Server error");
}
}
);
附加信息
user:req.user.id
作为参考exp\u id:req.params.exp\u id
,但没有成功。它给我一个“空”