samedi 28 février 2015

'or' query with different data types in sails.js

Given routes



GET /user/42
GET /user/dude


where 42 is user id and dude is username.


So, I want to have method in my controller that return user for both cases. Here it is:



// api/controllers/UserController.js
findOne: function(req, res) {
User.findOne({
or: [
{id: req.params.id},
{username: req.params.id}
]
}).exec(function(err, user) {
if (err) {
return console.log(err);
}
res.json(user);
});
},


When I try to GET /user/42 everything is fine.


When I try to GET /user/dude I get error:



Error (E_UNKNOWN) :: Encountered an unexpected error


error: invalid input syntax for integer: "dude"



It seems like sails refuses to process {id: 'dude'} because of type mismatch.


I am using sails 0.10.5 with sails-postgresql 0.10.9. So what am I doing wrong?


UPD: I do know how to solve problem. Of course I can put if statement to my controller and check what type of parameter it got. Actually, I just created two routes with regexp parameters that point to single method.


My actual problem is why I can not do this with or. Does sails provide such way?


Aucun commentaire:

Enregistrer un commentaire