Home > OS >  Can i have a mongoose model that refers itself?
Can i have a mongoose model that refers itself?

Time:04-15

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;
  1. I'm trying to have another field named "mentor" in the employee model, who will again be an employee (a user from employee model) , so how do I make a model refer itself?

i want something like this

    mentor :[{
    type: mongoose.Schema.Types.ObjectId, ref: 'Employee'
  }]

Does this work? what is the correct way to do this?

  1. also I wanted a teamMembers field which will be an array of 0 or more employees from employee model

how do i do this?

CodePudding user response:

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:

  1. Don't name your fields 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.
  2. I wouldn't recommend using all caps for a model name like 'EMPLOYEE' as this is not the recommended case for mongoose model names. They suggest upercase first letter, so Employee would be more correct.
  • Related