Im using node.js+express+mongodb+mongoose, trying to retrieve user from database by custom ids, page returns back completely empty due to incorrect datatype of id value, here is some part of my code:
var User = new Schema({
name: String ,
email: String ,
id: Number,
role: String
});
var userModel = mongoose.model('User', User);
var person = new userModel();
function loaduser(req, res, next) {
userModel.find({}, req.params.id, function(err, user){
if (user){
req.user = user;
console.log(user);
next();
}
})
console.log(typeof req.params.id);
};
//personal page route
app.get('/user/:id', loaduser, function(req, res){
res.render('show', { users: req.user });
});
and then this returns in console:
string
{ _id: 5012aa222c2d4d5876c5acd0,
email: 'alex@mail.com',
id: '0',
name: 'alex',
role: 'admin' },
even though i declared type of id as Number it gets back as String. Any suggestions are welcome :)
req.params.id
seems to be wrong in
userModel.find({}, req.params.id, function(err, user){
It should be
userModel.find({}, { id: parseInt(req.params.id) }, function(err, user){
Your find
call isn't quite right. The first parameter should be your query document and since you're looking for one document you should use findOne
instead. You also need to convert req.params.id
to a number:
userModel.findOne({ id: Number(req.params.id) }, function(err, user){
If you still see a problem with id
coming back as a string, it must be a string in the collection.