简体   繁体   English

从数组 MongoDB 中删除对象

[英]Remove Object from Array MongoDB

I need to remove a specific object from my mongoDB array.我需要从我的 mongoDB 数组中删除一个特定的对象。

Should remove the info above inside the red cube but (0: Object)应该删除上面红色立方体中的信息,但是 (0: Object)

MongoDB 架构

I tried the way I show below but didn't work.我尝试了下面显示的方式,但没有奏效。 And I need to remove the entire object but can't pass the values directly in the query so I need to grab the info from mongoDB and remove them.我需要删除整个对象,但不能直接在查询中传递值,所以我需要从 mongoDB 获取信息并删除它们。

router.post("/deleteArquive/:id", ensureAuthenticated, (req, res) => {
  var id = mongoose.Types.ObjectId(req.params.id);
  House.update(
    { "expensesHouse._id": id },
    {
      $pull: {
        expensesHouse: {
          status: "expensesHouse.status",
          _id: "expensesHouse._id",
          expenseType: "expensesHouse.expenseType"
        }
      }
    }
  ).then(house => {
    if (house.userID !== req.user.id) {
      res.redirect("/houses/houses");
    } else {
      req.flash("success_msg", "House removed!");
      res.redirect("/houses/houses");
    }
  });
}); 

If I understand the requirements correctly, this should do the job:如果我正确理解了要求,这应该可以完成工作:

House.update(
  { "expensesHouse._id": id },
  { 
    $pull: {
      expensesHouse: {
        _id: id
      }
    } 
  }
)

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

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