gpt4 book ai didi

node.js - Mongoose: CastError: 转换为 ObjectId 失败,路径 “me” 处的值 “_id”

转载 作者:太空宇宙 更新时间:2023-11-03 22:00:46 27 4
gpt4 key购买 nike

我知道这个问题有很多版本,但我找不到任何对我有帮助的东西。

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();
});
});
}

这是错误:

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)

我正在改编一些 Yeoman 样板授权代码,但我没有触及这部分。任何线索将不胜感激。

为了完整起见,这里是“我”的 api

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);
});
};

最佳答案

您正在尝试通过查询 _id 是否等于“me”来使用 findOne 访问对象。 Mongoose 尝试将字符串“me”转换为 ObjectId 但失败。我无法从回溯中判断是否是您的 me 函数出了问题(这是您提供的代码中唯一使用 findOne 的地方),但您可以尝试更改函数调用改为 User.findById(userId, ...) 。但是不明白为什么 userId 等于“me”,或者这是否有帮助。希望这至少给你一些方向。如果仍有问题,请添加评论。

关于node.js - Mongoose: CastError: 转换为 ObjectId 失败,路径 “me” 处的值 “_id”,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25795430/

27 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com