Reputation: 4313
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
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:
&
or ?
), when building the links, you should encode them. So the user name jill&bob
will yield the link localhost:8080/jill%26bob
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