我試圖通過 express 和 mongoose 在我的 MongoDB 通話中通過他們的電子郵件找到用戶。我通過請求正文獲取它,但目前它只回傳集合中的第一個用戶或集合中的所有用戶,我如何通過他們的電子郵件地址找到一個用戶?我顯然還想檢查他們的密碼......
用戶架構看起來像這樣
const users = mongoose.Schema({
Role: {
type: String,
default: 'Customer'
},
name: {
type: String,
required: true
},
password: {
type: String,
required: true
},
birthday:{
type: String,
required: true
},
displayName: String,
createdAt: {
type: Date,
default: Date.now
},
contact:{
email:{
type: String,
required: true
},
cellphone: String,
},
shippingAd:{
house:{
type: Number,
required: true,
},
road:{
type: String,
required: true,
},
complex: String,
city: {
type: String,
required: true,
},
province:{
type: String,
required: true,
},
postalCode:{
type: String,
required: true,
},
Country:{
type: String,
required: true,
},
},
newsletter:{
type: Boolean,
default: false
},
wishlist: [
{ type: mongoose.Schema.Types.ObjectId, ref: 'products'}
]
});
users.pre('save', async function(next){
try {
const salt = await bcrypt.genSalt(10);
const hashedPassword = await bcrypt.hash(this.password, salt);
this.password = hashedPassword;
next();
} catch (error) {
next(error);
}
})
呼叫的快速設定
userRouter.post('/api/loginuser',async (req, res) =>{
const findUser = await userSchema.findOne({
email: req.body.email
});
if(findUser){
return res.json(findUser)
} else{
res.json(false)
}
});
休息 API 呼叫
const loginUser = (e) =>{
let payload = {
email: formValues.email,
password: formValues.password
}
axios.post('http://localhost:5001/api/loginuser', payload)
.then(res =>{
if(!res.data){
alert('There was no response from the database.')
} else{
if(res.data){
sessionStorage.setItem('user', res.data.user)
// navigate('/')
console.log(res.data)
}else{
alert('Something is wrong in the backend')
}
}
})
.catch(err =>{
console.log(err);
})
}
uj5u.com熱心網友回復:
您的電子郵件欄位嵌套在您的聯系資訊中,因此為了通過電子郵件進行查詢以查找用戶,您必須像這樣搜索該嵌套值。
const findUser = await userSchema.findOne({
"contact.email": req.body.email
});
轉載請註明出處,本文鏈接:https://www.uj5u.com/net/503958.html
上一篇:使用FindMongooseExpress搜索時未定義
下一篇:過濾掉某些文本后如何合并資料集?
