Search code examples
node.jsapiexpressmongoosemongoose-schema

How to findOne in mongoDB Database


I´m currently working in the development of my own API and for that i want to save the userData in a especific way, i show u.

{
    "OzopdBz1oJSrbhCUd2Dr153DEicFA2du881a4Qr934O1FKo4rpELzAh06eQQ7v":{
        "userAccountData":{
            "userEmail": "myemail@mail.com",
            "userPassword": "QWERTY",  <--- Obvisly will be encrypted
            "userCellphoneNumber": 1234567890,
            "userFullName": "John White",
            "userBirthDate": "01-16-2003"
        },
        "userPublicData":{
            "userDisplayName": "JW",
            "userProfilePhotoURL": "https:www..."
        }
    }
}

My user Schema is the next one

const mongoose = require('mongoose')

const userSchema = mongoose.Schema({

    userAccountData:{
        userEmail: String,
        userPassword: String,
        userCellphoneNumber: Number,
        userFullName: String,
        userBirthDate: String,
        userRoles: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: "schemaRole"
        }]
      },
      userPublicData:{
        userDisplayName: String,
        userProfilePhotoURL: String
      }

})

module.exports = mongoose.model('User', userSchema)

As u can see the userEmail is inside the userAccountData and my proccess to validate if the email is alredy in the DB is the next

async function checkForDuplicatedEmail (req,res) {

    const userEmail = req.body.userEmail

    if(!userEmail) return res.json({
        status: 200,
        message: 'email not provided',
        data: {}
    })

    const isEmailDuplicated = await user.findOne({userEmail: userEmail})

    if(isEmailDuplicated) return res.json({
        status: 200,
        message: "true",
        data: {}
    })

    res.json({
        status: 200,
        message: "false",
        data: {}
    })
}

So the problem with this is that when i send the request the response is always true, even if the email is not in the db, am i doing something wrong? Can u help me?


Solution

  • This is the way I solve the problem

    The userSchema is wrong and most be like this

    const userAccountDataSchema = mongoose.Schema({
        userEmail:String,
        userPassword: String,
        userCellphoneNumber: Number,
        userFullName: String,
        userBirthDate: String
    })
    
    const userPublicDataSchema = mongoose.Schema({
        userDisplayName: String,
        userProfilePhotoURL: String
    })
    
    const userSchema = mongoose.Schema({
        userAccountData:userAccountDataSchema,
        userPublicData:userPublicDataSchema
    })
    

    Then, the findOne must be like this:

    const isEmailDuplicated = await user.findOne({
        'userAccountData.userEmail': userEmail
    })