我知道有很多这样的问题,但从我的尝试来看,似乎没有任何效果。
应用程序的快速概览,nodejs 后端使用 365 护照身份验证对用户进行身份验证,然后在 ReactJS 前端中使用。
我在 udemy 上关注 Node with React 全栈网络开发类(class),它一直在工作,直到我开始收到以下错误:
"Cast to ObjectId failed for value "00037ffe-0944-74f2-0000-000000000000@84df9e7f-e9f6-40af-b435-aaaaaaaaaaaa" at path "_id" for model "office" "
我是 MongoDB 和 Mongoose 的新手,所以我真的不知道该看什么。我认为它在我的 passport.use auth 部分的某个地方。
一旦我重建了 MongoDB 及其所有相关内容(基本模式等),错误就会消失。 (我的意思是与新的 mongo 集合/实例完全相同的代码。)
然后我得到了 365 护照认证工作,但过了一会儿,同样的错误会出现。如果您需要更多片段,请告诉我,这是我目前所拥有的:
这是我的护照Outlook攻略:
passport.use(
new OutlookStrategy(
{
clientID: keys.OUTLOOK_CLIENT_ID,
clientSecret: keys.OUTLOOK_SECRET,
callbackURL: "/authorize-outlook"
},
async (accessToken, refreshToken, profile, done) => {
const exist = await Office.findOne({ outlookID: profile.id }).catch(
error => console.log("error: ", error)
);
if (exist) {
return done(null, exist);
} else {
const user = new Office({
outlookID: profile.id,
displayName: profile.displayName
}).save();
done(null, user);
}
}
)
);
序列化/反序列化:
passport.serializeUser((user, done) => {
//turns user into id
// see mlabs _id, identifying ID added my mongo
// this is not profile id from google
done(null, user.id);
});
// ID into a mongoose instance
// id placed in cookie above in "serializeUser" i.e the user.id
passport.deserializeUser((id, done) => {
//turns id into user (mongoose model instance)
Office.findById(id).then(user => {
done(null, user);
});
});
我的架构:
const mongoose = require("mongoose");
const { Schema } = mongoose;
OfficeSchema = new Schema({
outlookID: String,
displayName: String
});
mongoose.model("office", OfficeSchema);
最后是我的身份验证路由:
app.get(
"/auth/outlook",
passport.authenticate("windowslive", {
scope: [
"openid",
"profile",
"offline_access",
"https://outlook.office.com/Mail.Read"
]
})
);
// Use passport.authenticate() as route middleware to authenticate the
// request. If authentication fails, the user will be redirected back to the
// login page. Otherwise, the primary route function will be called,
// which, in this example, will redirect the user to the home page.
app.get(
"/authorize-outlook",
passport.authenticate("windowslive"),
(req, res) => {
res.redirect("/dashboard");
}
);
};
我知道这比必要的要多,但我现在宁愿尽可能多地给予。
如果您有修复/改进,请将它们发送给我。
如有任何帮助,我们将不胜感激。谢谢你的时间。
最佳答案
尝试更改以下代码
当前:
passport.deserializeUser((id, done) => {
//turns id into user (mongoose model instance)
Office.findById(id).then(user => {
done(null, user);
});
});
预期
passport.deserializeUser((id, done) => {
//turns id into user (mongoose model instance)
Office.findById(mongoose.Types.ObjectId(id)).then(user => {
done(null, user);
});
});
我觉得应该可以
关于node.js - 转换错误 : Cast to ObjectId failed at path "_id",我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51589887/