0

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

quietplace
  • 471
  • 1
  • 4
  • 14

1 Answers1

2

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