I'm doing a MERN stack app. I have a Profile model with a field called experience (which is an array). When I call an api to add 1 new experience object, an ObjectId was also generated though experience is not a collection. How could I know when Mongoose (or MongoDB) will auto generate that ObjectId?
Here's my Schema:
const ProfileSchema = Schema({
user: {
type: Schema.Types.ObjectId,
ref: 'user'
},
handle: {
type: String,
required: true,
max: 40
},
bio: {
type: String
},
company: {
type: String
},
website: {
type: String
},
location: {
type: String
},
status: {
type: String,
required: true
},
skills: {
type: [String],
required: true
},
githubusername: {
type: String
},
experience: [
{
title: {
type: String,
required: true
},
company: {
type: String,
required: true
},
location: {
type: String
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
}
],
education: [
{
school: {
type: String,
required: true
},
degree: {
type: String,
required: true
},
fieldofstudy: {
type: String,
required: true
},
from: {
type: Date,
required: true
},
to: {
type: Date
},
current: {
type: Boolean,
default: false
},
description: {
type: String
}
},
],
social: {
youtube: {
type: String
},
twitter: {
type: String
},
facebook: {
type: String
},
linkedin: {
type: String
},
instagram: {
type: String
}
},
date: {
type: Date,
default: Date.now
}
});
The api:
router.post(
'/experience',
passport.authenticate('jwt', { session: false }),
(req, res) => {
// Validate first
let {errors, isValid} = Validator.validateExperience(req.body);
if (!isValid) {
return res.status(400).json(errors);
}
Profile.findOne({ user: req.user.id })
.then(profile => {
if (!profile) {
errors.noprofile = 'There is no profile of this user.';
return res.status(404).json(errors);
}
let newExp = {
title: req.body.title,
company: req.body.company,
location: req.body.location,
from: req.body.from,
to: req.body.to,
current: req.body.current,
description: req.body.description,
};
// Add to experience array
profile.experience.unshift(newExp);
profile.save().then(profile => res.json(profile));
})
}
);
After added:
"experience": [
{
"current": true,
"_id": "5b126c5fd16a74472136a6bb",
"title": "Front-end Developer",
"company": "Nash Tech",
"from": "2017-09-18T00:00:00.000Z",
"description": "Develop websites with current technology."
},
...