MongoDB finding first user instead of the specified Email user

Issue

Im trying to find a user by their email in my MongoDB call through express and mongoose. Im getting it through a request body but at the moment it’s only returning the first user in the collection or all the users in the collection, how do I find ONE user by their email address? I would obviously also like to then check their passwords…

User Schema looks like this

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

Express setup for the call

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

Rest API call

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

Solution

Your email field is nested within your contact info so in order to make a query to find a user by the email you have to search for that nest value like this.

const findUser = await userSchema.findOne({
        "contact.email": req.body.email
    });

Answered By – Cydo Entis

This Answer collected from stackoverflow, is licensed under cc by-sa 2.5 , cc by-sa 3.0 and cc by-sa 4.0

Leave a Reply

(*) Required, Your email will not be published