user2472335
user2472335

Reputation:

deleting MongoDB entry when URL is visited - node.js

I'm working on making a simple Twitter clone for a project using node.js and express, and storing the tweets using MongoDB.

I am trying to implement deleting functionality for the tweets. a user's profile displays all their tweets, and I was hoping to put a little button or link under each tweet that a user will click for deleting.

So, I was thinking the easiest way to do this would be specifying a "delete URL" for each tweet, like ..../profile/delete/[mongoDB object id here]. And then in node,say that when the router receives a get request for a URL like that, remove the object with the specified id from the database.

I have heard you can use regular expressions to match and parse URLs to do this, but I can't really find any resources on how. So how can I write a regular expression to match these URLs, and then parse the URL to get the object ID? Or is there a better way to do this?

Upvotes: 0

Views: 98

Answers (1)

pedrommuller
pedrommuller

Reputation: 16066

I'm not sure what you want to do with regex in the route, but let me write a case for you and probably sort this out:

  • first Define a route in express let's say 'profile/tweet/delete/:id'
  • Restrict that route only yo delete http verb
  • Do a request.params.id to get the id

something like:

exports.deleteTweet = function(req,res){
    if(req.params.tweetId !==null || req.params.tweetId!==undefined){
        //assuming mongoose here
        TweetSchema.remove({_id:req.params.TweetId},function(err){
            res.send(200);
        });
    }
};

route:

app.route('/profile/tweet/:tweetId').delete(myController.deleteTweet);

Upvotes: 1

Related Questions