I'm trying to do a find by username or _id like this
exports.getUser = function (req, res){
User.find({ $or: [ {username:req.params.id}, {_id:req.params.id} ] })
.exec(function (err, collections) {
res.send(collections);
});
};
It works when I search by _id but fails for username because it fails to return a valid OjectID. I tried doing two separate queries like this
exports.getUser = function (req, res){
User.findOne({username:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
};
but this hangs if the user doesn't exist because it never sends a response. Since node is async I get Error: Can't set headers after they are sent.
if I add
else
res.sendStatus(400);
to the findById query. I can't think of any other way to solve this.I tried the regex in MongoDB Node check if objectid is valid
exports.getUser = function (req, res){
var checkForHexRegExp = new RegExp("^[0-9a-fA-F]{24}$");
if(checkForHexRegExp.test(req.params.id)){
User.findById({_id:req.params.id}).exec(function (err, user) {
if (user)
res.send(user);
});
}
User.findOne({username:req.params.id}).exec(function (err, user) {
res.send(user);
});
};
And I'm getting the same error because it's async. There has to be a better way than this