0

I am using Node.js, express, mongodb, and mongoose. I have two files: favorite and favorite-route.

"favorites" in the schema has multiple objects in it array. Given the mongodb assigned _id, I would like to create a delete method to gremove the specified object in the array.

Here is my schema in favorite:

    userID:{
        //type: String,
        
        type: mongoose.Schema.Types.ObjectId,
        ref: "user",
        required: true,
        unique: true
    },
    favorites:[{
        
        publication: {
            type:mongoose.Schema.Types.ObjectId,
            ref: "Pet"
        },

        id: {
            type: String,
            required: true
        },
        comment: {
            type: String,
            required: true
        }
    }]   
})
favoritesSchema.statics.deleteFavorite = async (favID)=>{
    return await Favorite.findOneAndUpdate({favID})
}

This is my delete method in favorite-route file:

router.delete('/:favID', async (req,res)=>{

    let doc = await Favorite.deleteFavorite(req.params.favID)

    if(doc){
        doc.splice(req.params.favID);
        res.send(doc)
        return;
    }

    res.status(404).send({error: "no se encontró esa publicación"})
})

And lastly, here is my http:

DELETE {{host}}/api/favorites/626eddd14762eb4ae4c77f9e

When i test this, it gives me the error: TypeError: doc.splice is not a function

I'd appreciate any tips and insight. I have spent a while searching for answers but most suggested using $pull, which I am unsure how to implement in the delete method.

Thank you :)

1
  • The problem is that you should be passing also the parent object id as a parameter to the route to findById it and the remove the specified element in the favorites array Commented May 2, 2022 at 7:19

1 Answer 1

0

you should do.

    Favorite.updateOne(
      { userID: user._id }, // this is the query to find the desired favourite list
      { $pull: { favorites: { id : req.params.favID }} }, // this removes  
     
    );


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

4 Comments

Thanks for taking the time to answer! Where do I need to include that in my existing code? I am assuming in my DELETE method?
here favoritesSchema.statics.deleteFavorite = async (favID)=>{
unfortunately req.params.favid isnt defined in that file.
pass it as an argument in the delete method and in model n, replace req.params.favID with favID

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.