Adding more datas in an array using Mongoose

Viewed 28

The problem

When I try to add more employees datas to an user, the old employee data is deleted.

User.js

I have these properties in my User model.

...
employee: [{
  workplace: {
    type: mongoose.SchemaTypes.ObjectId,
    ref: 'Saloon',
  },
  workAs: {
    type: String,
  }
}]
...

Because when the User is an employee, it can be work at N places. I am trying to add two places to show if it is working, but do not work.

addEmployee.js

const employeeData = await User.findByIdAndUpdate(userId, 
  {
    employee: [{
      workplace: companyId,
      workAs, 
    }],
  }
);

This is my method to add a new employee, but when I try, is added but when I try to add a new, the old data is deleted.

employee: Array
 0: Object
   _id: 5fc3ae2c694e3a11291c9f05
   workplace: 5fc2c6e58f4fb3520ecb45ce
   workAs: "ant-work-as"

I would like this for an example

employee: Array
 0: Object
   _id: 5fc3ae2c694e3a11291c9f05
   workplace: 5fc2c6e58f4fb3520ecb45ce
   workAs: "ant-work-as"
 1: Object
   _id: any-id
   workplace: any-workplace
   workAs: "any-work-as"
1 Answers

With you current syntax, you're setting the employee field to the document you pass as value. As employee is an array, you have to use the $push array update operator

db.collection.update({
  _id: ObjectId("5a934e000102030405000000")
},
{
  $push: {
    employee: {
      "_id": "5fc3ae2c694e3a11291c9f06",
      "workplace": "5fc2c6e58f4fb3520ecb45ce",
      "workAs": "ant-work-as-2"
    }
  }
})

You can test it here.

Related