Reputation: 23
I have a model that looks like this
const employeeSchema = new mongoose.Schema({
empFirstName:{
type: String,
reuired: true
},
empLastName:{
type: String,
reuired: true
},
empEmail:{
type: String,
reuired: true
},
empPassword:{
type: String,
reuired: true
},
empConfirmPass:{
type: String,
reuired: true
},
empContactNum:{
type: Number,
reuired: true
},
empPosition:{
type: String,
reuired: true
},
empTeam:{
type: String,
reuired: true
}
});
const Employee = mongoose.model('EMPLOYEE', employeeSchema);
module.exports = Employee;
i want something like this
mentor :[{
type: mongoose.Schema.Types.ObjectId, ref: 'Employee'
}]
Does this work? what is the correct way to do this?
how do i do this?
Upvotes: 1
Views: 442
Reputation: 1317
This will work. You had it correct in your question:
const employeeSchema = new Schema ({
mentor: [{ type: Schema.Types.ObjectId, ref: 'Employee' }],
teamMembers: [{ type: Schema.Types.ObjectId, ref: 'Employee' }],
})
I've added some routes as well just to give you an idea on how to use it.
// add team member to employee
index.post('/addTeamMember', (req, res) => {
Employee.findById(req.body.employeeId, (err, employee) => {
if (err) {
console.log(err);
} else {
employee.teamMembers.push(req.body.teamMemberId);
employee.save((err) => {
if (err) {
console.log(err);
} else {
res.redirect('/');
}
});
}
});
});
// add mentor to employee
index.post('/addMentor', (req, res) => {
Employee.findById(req.body.employeeId, (err, employee) => {
if (err) {
console.log(err);
} else {
employee.mentor.push(req.body.mentorId);
employee.save((err) => {
if (err) {
console.log(err);
} else {
res.redirect('/');
}
});
}
});
});
You can also populate
those fields:
index.get('/populate', (req, res) => {
Employee.findById(req.body.employeeId)
.populate('mentor')
.populate('teamMembers')
.exec((err, employee) => {
if (err) {
console.log(err);
} else {
res.send(employee);
}
});
});
and just some suggestions:
emFirstName
, emLastName
, etc. This is redundant as you already have your model named Employee. It also makes your code less legible. Instead just use firstName
, lastName
, etc.'EMPLOYEE'
as this is not the recommended case for mongoose model names. They suggest upercase first letter, so Employee
would be more correct.Upvotes: 1