Home > database >  findOne returning me null even though there is entries in my DB NodeJS
findOne returning me null even though there is entries in my DB NodeJS

Time:11-05

This is my User Model

    module.exports = (sequelize, DataTypes) => {
    const User = sequelize.define("User", {
        email: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },
        password: {
            type: DataTypes.STRING,
            allowNull: false
        }
    })
    return User
}

and i am try to find if there is any entry in my User table of given email

app.post("/login", (req, res) => {
    let email = req.body.email
    User.findOne({ where: { email: email } }).then((result) => {
        if (result == null) {
            console.log("data is null", result)
            res.send("No data found")
        } else {
            res.send(result)
        }
    }).catch((err) => {
        console.log(err, "Error in find one")
    })
})

this is the the output in my terminal

Executing (default): SELECT `id`, `email`, `password`, `createdAt`, `updatedAt` FROM `Users` AS `User` WHERE `User`.`email` = 'This is my User table in DB

CodePudding user response:

I have encountered this error before and when I set the timestamp false on my defined model fix my issue also you can check this link for more information

CodePudding user response:

This is a common mistake so don't worry. With sequelize the first argument of the sequelize.define function should represent one row in your table. So if your table is called users then you need to use user. Note the lowercase. Modify like so:

    const User = sequelize.define("user", { //< lowercase 'user'
       //...
       //...
    })

Read here for official docs.

As an aside, it will also work work with users as well as user.

  • Related