Home > Blockchain >  Mongoose how to return all collection data after deleting one item
Mongoose how to return all collection data after deleting one item

Time:01-19

I create a delete api and it works to delete the item in mongoose atlas, but it has 404 error when I add profile.save() to get all current items.

Node.js code:

router.delete('/delete/:id',(req, res) => {
    Profile.findOneAndDelete({_id:req.params.id}).then(profile => {

      // res.json(profile) this line works to return the deleted item but I want to use below line to return all data.

       profile.save().then(profiles => res.json(profiles)).catch(err=>res.status(404).json(err))
    })
.catch(err => res.status(404).json(err))
})

Result:

{
"result": {
    "$where": {
        "_id": "61e7b297f880e56c8f6f6b2e"
    },
    "matchedCount": 0
},
"numAffected": 0,
"filter": {
    "_id": "61e7b297f880e56c8f6f6b2e"
},
"query": {
    "_id": "61e7b297f880e56c8f6f6b2e"
}
}

I noticed that in some tutorials it worked when adding that line, but in my case it failed.

CodePudding user response:

You need to use find query to return all data. save function is used to update or save item to DB.

The save() method returns a promise. If save() succeeds, the promise resolves to the document that was saved.

When you delete the document, it returns the deleted user only. If you want to save it again, you need to create a model and put the values there and call the save function.

I add profile.save() to get all current items. It only returns the saved documents, it won't return you all the documents from the collection.

If you want to get all the profile data, call find query.

router.delete('/delete/:id', async (req, res) => {
  try {
    const deletedProfile = await Profile.findOneAndDelete({_id:req.params.id}); // conatins only deleted profile
    const getAllProfile = await Profile.find({}); // get all profile
    // now you can return all the profiles 
  } catch (error) {
    res.status(404).json(error);
  }    
 })
  •  Tags:  
  • Related