簡體   English   中英

貓鼬:如何從值中刪除數組中的項

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

有沒有一種方法可以用Mongoose從數組中刪除項目? 我有這樣的對象內部數組:

“學生”:[“ 5ad72254452996029415e49f”,“ 5adaeb388acfc414d428820b”]

我想通過確定的值刪除其中之一。 這是我的代碼:

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

學生是一個數組,我想通過ID更新和刪除其中的一個數組元素。

是的,您必須在array屬性上執行$ pull

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

然后進行更新,例如:

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