sinusGob
sinusGob

Reputation: 4313

Url parameter in express and mongoose

Im building a basic web app with node/express and mongoose. How do i replace :id in express parameter to a string

For example

mongoose model

var UserSchema = new Schema({
   name: String,
});

var User = mongoose.model('User', UserSchema);

Let say there is a user name "Mr robot king" in the User's collection right now

app.get('/:id', function(req, res, next) {
    User.findOne({ _id: req.params.id }, function(err, user) {
       res.render('home');
    });
});

result of the url

localhost:8080/5asdasd43241asdasdasd

What i want is

localhost:8080/Mr-robot-king

Upvotes: 1

Views: 2974

Answers (1)

robertklep
robertklep

Reputation: 203519

In essence, that wouldn't be too difficult:

app.get('/:name', function(req, res, next) {
  var name = req.params.name.replace(/-/g, ' ');
  User.findOne({ name : name }, function(err, user) {
    res.json(user);
  });
});

Some considerations:

  • Since your example replaces spaces with hyphens, and the code above does the opposite, user names with actual hyphens in them will break this substitution scheme;
  • If user names are allowed to contain characters that have special meaning in URL's (like & or ?), when building the links, you should encode them. So the user name jill&bob will yield the link localhost:8080/jill%26bob
  • You probably want to add an index to the name field to make sure that queries are fast;

EDIT: to generate these links, for instance from an EJS template, you can use something like this:

<a href="/<%= user.name.replace(/ /g, '-') %>">go to page</a>

Upvotes: 3

Related Questions