1

I have the following document structure:

enter image description here

And am trying to figure out how to delete a single object from the 'saved array', using the id in the object to select it (eg id 4182 will delete the object and all its properties at index 0). This was my attempt but not sure how to target it properly (No errors, but nothing updated):

      let id = req.query.clicked_id;  
      console.log("\deleteSaved id:", id);  
   
      db.collection("users").updateOne(
         { username: config.username },
         { $unset: { id: id} }, 
            (err, data) => {
              if (err) {
                console.log(err);
              }
              console.log("Item deleted from DB: ", id, data.result.nModified);
              res.redirect("/saved");
      }) ; 

Thanks

1 Answer 1

3

you can find the answer very clear in the (MongoDB, remove object from array)

and my answer is

you can use $pull operator in mongodb documentation to pull element from array you can use this query

      let id = req.query.clicked_id;  
      console.log("\deleteSaved id:", id);  
   
      db.collection("users").updateOne(
         { username: config.username },
         { $pull: {saved: { id: id } }, 
            (err, data) => {
              if (err) {
                console.log(err);
              }
              console.log("Item deleted from DB: ", id, data.result.nModified);
              res.redirect("/saved");
      }) ; 

this one will work fine

Sign up to request clarification or add additional context in comments.

1 Comment

Thanks. That worked great. Just needed the extra closing bracket for the $pull operator.

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.