我在我的代码中除登录路由之外的每个路由中都使用了一个名为checktoken的中间件。当我点击登录URL时,它会将我登录到有令牌检查的位置。但现在如果我希望在登录后去任何路线它限制我在checkToken中间件.i已经使用jsonwebtoken模块生成令牌并验证它。但我的代码无法找到users.here是我的checktoken中间件代码
if (token) {
try {
var decoded = jsonwebtoken.verify(token, jwt_key);
req.user = decoded.user;///
console.log(req.user._id);// i get id here and from this id i can find user in database
UserSchema.findOne({
_id: req.user._id
})///this query failed finding result
.exec(function(err, result) {
if (err) {
console.log(err);//error gets output in the console.
res.status(500);
return res.json({
result: err
});
}
if (result) {
return next();
} else {
res.status(400);
return res.json({
message: "The user does not exists"
});
}
});
} catch (err) {
res.status(403);
res.json({
message: "Invalid Token"
});
}
} else {
res.status(401);
res.json({
message: "No token provided"
});
}
我在控制台中收到的错误信息是
{ [CastError: Cast to ObjectId failed for value "5875d76e1df97635623061c5" at path "_id" for model "User"]
message: 'Cast to ObjectId failed for value "5875d76e1df97635623061c5" at path "_id" for model "User"',
name: 'CastError',
stringValue: '"5875d76e1df97635623061c5"',
kind: 'ObjectId',
value: '5875d76e1df97635623061c5',
path: '_id',
reason: undefined,
model:
{ [Function: model]
hooks: Kareem { _pres: {}, _posts: {} },
base:
Mongoose {
connections: [Object],
plugins: [],
models: [Object],
modelSchemas: [Object],
options: [Object] },
modelName: 'User',
model: [Function: model],
db:
NativeConnection {
base: [Object],
collections: [Object],
models: [Object],
config: [Object],
replica: false,
hosts: null,
host: 'localhost',
port: 27017,
user: undefined,
pass: undefined,
name: 'myschoolbus_demo',
options: [Object],
otherDbs: [],
_readyState: 1,
_closeCalled: false,
_hasOpened: true,
_listening: false,
db: [Object] },
discriminators: undefined,
schema:
Schema {
obj: [Object],
paths: [Object],
subpaths: {},
virtuals: [Object],
singleNestedPaths: {},
nested: [Object],
inherits: {},
callQueue: [Object],
_indexes: [],
methods: [Object],
statics: {},
tree: [Object],
_requiredpaths: undefined,
discriminatorMapping: undefined,
_indexedpaths: undefined,
query: {},
childSchemas: [],
s: [Object],
options: [Object],
'$globalPluginsApplied': true },
collection:
NativeCollection {
collection: [Object],
opts: [Object],
name: 'users',
collectionName: 'users',
conn: [Object],
queue: [],
buffer: false,
emitter: [Object] },
Query: { [Function] base: [Object] },
'$__insertMany': [Function],
insertMany: [Function] } }
我无法弄清楚我错在哪里。任何建议都非常感谢。
答案 0 :(得分:0)
从您的ID中删除引号。你的错误说:
stringValue: '"5875d76e1df97635623061c5"',
在开始和结束时查看"
?它是字符串的一部分。我不知道你的中间件,或前端或者是谁,所以要么自己剥离它,要么之前通过它。
Try this:
UserSchema.findOne({
_id: req.user._id.replace(/"/g, '')
})