简体   繁体   中英

Mongoose : How to remove item from array by value

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.

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) => {
                           }
                     );

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM