I know there are a lot of version of this question, but I couldn't find anything helping me.
function isAuthenticated() {
return compose()
// Validate jwt
.use(function (req, res, next) {
// allow access_token to be passed through query parameter as well
if (req.query && req.query.hasOwnProperty('access_token')) {
req.headers.authorization = 'Bearer ' + req.query.access_token;
}
validateJwt(req, res, next);
})
// Attach user to request
.use(function (req, res, next) {
User.findById(req.user._id, function (err, user) {
console.log(next);
if (err) {
return next(err);
}
if (!user) {
return res.send(401);
}
req.user = user;
next();
});
});
}
Here is the error :
CastError: Cast to ObjectId failed for value "me" at path "_id"
at ObjectId.cast (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongoose\lib\
schema\objectid.js:116:13)
at ObjectId.castForQuery (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongo
ose\lib\schema\objectid.js:165:17)
at Query.cast (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongoose\lib\que
ry.js:2317:32)
at Query.findOne (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongoose\lib\
query.js:1118:10)
at Function.findOne (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongoose\l
ib\model.js:1049:13)
at Function.findById (C:\Users\Benoit\Desktop\Gakusei\node_modules\mongoose\
lib\model.js:986:15)
at Object.exports.show [as handle] (C:\Users\Benoit\Desktop\Gakusei\server\a
pi\user.js:43:8)
at next_layer (C:\Users\Benoit\Desktop\Gakusei\node_modules\express\lib\rout
er\route.js:103:13)
at next (C:\Users\Benoit\Desktop\Gakusei\node_modules\composable-middleware\
lib\composable-middleware.js:40:9)
at Promise.<anonymous> (C:\Users\Benoit\Desktop\Gakusei\server\auth\auth.ser
vice.js:37:9)
I'm adapting some of Yeoman boilerplate auth code and I didn't touch this part. Any clues would be greatly appreciated.
for completness, here my api for 'me'
exports.me = function (req, res, next) {
var userId = req.user._id;
User.findOne({
_id: userId
}, '-salt -hashedPassword', function (err, user) {
if (err) {
return next(err);
}
if (!user) {
return res.json(401);
}
res.json(user);
});
};
You are trying to access a object with findOne by querying _id to be equal to 'me'. Mongoose is attempt to convert the string 'me' to an ObjectId but fails. I can't tell from the traceback if it's your me function which is the issue (that's the only place where findOne is used in the code you have provided), but you could try to change the function call to User.findById(userId, ...) instead. Don't see why userId is equal to 'me' however or if that would help any at all. Hope this gave you some direction at least. Add a comment if you still have problems.