简体   繁体   English

猫鼬:如何从值中删除数组中的项

[英]Mongoose : How to remove item from array by value

Is there a method to remove an item from an array with Mongoose? 有没有一种方法可以用Mongoose从数组中删除项目? I have an array inside object like this: 我有这样的对象内部数组:

"students": [ "5ad72254452996029415e49f", "5adaeb388acfc414d428820b" ] “学生”:[“ 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. 学生是一个数组,我想通过ID更新和删除其中的一个数组元素。

Yes, you must do a $pull on your array attribute: 是的,您必须在array属性上执行$ pull

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

Then do an update, for example: 然后进行更新,例如:

return Company.findOneAndUpdate({ _id: companyId }, 
                                deleteStudentStatement, 
                                { new: true })
                     .then((company) => {
                           },
                           (err) => {
                           }
                     );

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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