我有一個看起來像這樣的 JSON:
{
_id: new ObjectId("6374633c7cf80673ee9a22c9"),
consultant_name: 'Jackson',
consultantUsername: 'paul',
consultant_Password: '123',
clients: [
{
client_name: 'Amine Bouabou',
client_Username: 'amine',
client_Password: '123',
documents: [Array],
_id: new ObjectId("6374633c7cf80673ee9a22ca")
},
{
client_name: 'Latifa Alaoui',
client_Username: 'latifa',
client_Password: '1234',
documents: [Array],
_id: new ObjectId("6374633c7cf80673ee9a22cd")
}
],
createdAt: 2022-11-16T04:12:44.645Z,
updatedAt: 2022-11-16T04:12:44.645Z,
__v: 0
}
我想要做的是 1) 在用戶嘗試登錄時找到具有 client_Username 的物件(例如我現在可以做的“amine”或“latifa”)并比較該特定 client_Username 的特定密碼( “123”或“1234”,這個我做不到)。我使用 passeport 進行身份驗證,這是我的代碼的樣子:
const User = require('./models/user');
const localStrategy = require("passport-local").Strategy;
module.exports = function (passport) {
passport.use(
new localStrategy((username, password, done) => {
User.findOne({ "clients.client_Username": username }, (err, user) => {
if (err) throw err;
if (!user) return done(null, false);
if (user) console.log("we have a user");
// the user answer that I get here is the exact json posted above
if (user) console.log(user);
// line underneath doesn't work, I want to compare the password that user is using for login with // the proper specific password of that client_username (so either 123 or 1234)
if (password === user.clients.client_Password) {
console.log("password match");
return done(null, user);
}else {
console.log("no password match");
return done(null, false);
}
});
})
);
passport.serializeUser((user, cb) => {
cb(null, user.id);
});
passport.deserializeUser((id, cb) => {
User.findOne({ _id: id }, (err, user) => {
const userInformation = {
username: user.username,
password: user.password,
documents: user.documents,
};
cb(err, userInformation);
});
});
};
我確實嘗試將其作為測驗來運行并且它有效:
module.exports = function (passport) {
passport.use(
new localStrategy((username, password, done) => {
console.log("this is my " username);
console.log("this is my " password);
User.findOne({ "clients.client_Username": username }, (err, user) => {
if (err) throw err;
if (!user) return done(null, false);
// change here
if (password === user.clients[0].client_Password) {
console.log("password match");
return done(null, user);
}else {
console.log("no password match");
return done(null, false);
}
});
})
);
顯然,當我指定該用戶的索引時,它就起作用了。基本上我所尋求的是相同的結果,但不必對索引進行硬編碼。
uj5u.com熱心網友回復:
在將密碼與提供的密碼進行匹配之前,您必須從clients陣列中獲取正確的條目。它看起來像這樣:
const client = user.clients.filter((el) => el.client_Username === username)[0]
if (password === client.client_Password) {
...
另一種選擇是在 Mongo 查詢上使用聚合函式來獲取已過濾的串列。但是,我不確定您用于 Mongo 的庫是否支持它。你必須自己檢查一下。(這里是 Mongo$filter聚合的檔案:https: //www.mongodb.com/docs/manual/reference/operator/aggregation/filter/)。從理論上講,使用 mongo 過濾器應該具有更好的性能,因為您不必再??在 JS 代碼中過濾陣列。
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/536489.html
下一篇:如何防止用戶在查詢中修改外鍵?
