1

Is there a method to remove an item from an array with Mongoose? I have an array inside object like this:

"students": [ "5ad72254452996029415e49f", "5adaeb388acfc414d428820b" ]

And I'd like to remove one of them by identified value. This is my code :

Company.findById(id_company, function(err, company) {
  var students = company.students; //students array
  // ...
  // ...
  // ...
});

Students is an array, and I'd like to update and remove one of array element inside it by ID.

Eduardo Yáñez Parareda
  • 5,636
  • 4
  • 32
  • 41
Fatih
  • 131
  • 1
  • 2
  • 12

1 Answers1

0

Yes, you must do a $pull on your array attribute:

const deleteStudentStatement = {
    $pull: {students: studentId}
};

Then do an update, for example:

return Company.findOneAndUpdate({ _id: companyId }, 
                                deleteStudentStatement, 
                                { new: true })
                     .then((company) => {
                           },
                           (err) => {
                           }
                     );
Eduardo Yáñez Parareda
  • 5,636
  • 4
  • 32
  • 41