this is my schema
const mongoose = require ('mongoose');
const adminSchema = new mongoose.Schema({
name:String,
password:String,
user:[{
name:String,
email:String,
password:String
}
]
})
var user = mongoose.model("Admin",adminSchema)
module.exports = user
;
admin login works properly the problem is admin can (its available outside as per the schema ) login as user and user is not able to login(cuz its inside as an array ) here is my data base collection:
> db.admins.find().pretty()
{
"_id" : ObjectId("62ad807e5c40fa9cdd5fb584"),
"name" : "admin",
"password" : "$2b$10$wJLM8sXoRbFjFlK6jyjEb.a6n60SlckVBfG1wbDd4A/0e5UOAABGC",
"__v" : 0,
"user" : [
{
"name" : "jghuter",
"email" : "[email protected]",
"password" : "$2b$10$m3sna5erYQ4RJ95WIqP6MeAHvbTTfrsKn4F7y7yPpZoxvYcRltsba",
"_id" : ObjectId("62ad9d0c3b127dc669f423c7")
}]}
this is my login comparison
doLogin : (userData)=>{
return new Promise(async(resolve,reject)=>{
let loginStatus = false
let response = {}
let user = await admin.aggregate([
{$match: {'user.email': userData.email}},
{$project: {
user: {$filter: {
input: '$user',
as: 'user',
cond: {$eq: ['$$user.email', userData.email]}
}},
_id: 0
}}
])
if(user){
bcrypt.compare(userData.password,user.password).then((status)=>{
if (status){
console.log('login success');
response.user = user
response.status = true
resolve(response)
}else
console.log('login failed');
resolve({status:false})
})
}else{
console.log('login failed');
resolve({status:false})
}
})
}
how to compare it with the result
CodePudding user response:
You can query the user's array like this
let admins = await db.admins.aggregate([
{$match: {'user.email': '[email protected]'}},
{$project: {
user: {$filter: {
input: '$user',
as: 'user',
cond: {$eq: ['$$user.email', '[email protected]']}
}},
_id: 0
}}
])
it will return something like
[
{
"user" : [
{
"name" : "jghuter",
"email" : "[email protected]",
"password" : "$2b$10$m3sna5erYQ4RJ95WIqP6MeAHvbTTfrsKn4F7y7yPpZoxvYcRltsba",
"_id" : ObjectId("62ad9d0c3b127dc669f423c7")
}
]
}
]
comparing password
if(admins.length){
const users = admins[0]?.user;
if(users.length){
const user = users[0];
bcrypt.compare(input.password,user.password);
}
}