0

I need to remove a specific object from my mongoDB array.

Should remove the info above inside the red cube but (0: Object)

MongoDB Schema

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.

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");
    }
  });
}); 
4
  • Where do you get "expensesHouse.status" and the other two values from ? Commented Feb 1, 2020 at 1:27
  • The way I show above is what I tried but I don't know how I can get the specific values I pass into. Commented Feb 1, 2020 at 10:44
  • @CarlosOrelhas What do you need those values for? You have the id, don't you? Commented Feb 1, 2020 at 10:46
  • @Mafor I have the specific ID and what I need is remove the expense from my house but only the right one (id should match) Commented Feb 1, 2020 at 12:08

1 Answer 1

2

If I understand the requirements correctly, this should do the job:

House.update(
  { "expensesHouse._id": id },
  { 
    $pull: {
      expensesHouse: {
        _id: id
      }
    } 
  }
)
Sign up to request clarification or add additional context in comments.

1 Comment

It works!! I just think I need to $pull every field so it gets me lost! :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.