Home > Software engineering >  TypeError: Cannot read properties of undefined (reading 'findAll') <nodejs>
TypeError: Cannot read properties of undefined (reading 'findAll') <nodejs>

Time:08-21

I was trying to make an API using Node.js and Sequelize (MySQL). The API has many models and associations. I made migrations after making the models. Now that I'm making the service file, when I make a request to the login route, I encounter that error. I have tried many things and read a lot of guides for this issue. But I still have that.

(Typos checked!) -- (The modules imported properly)

Could you please suggest me a solution? I appreciate you in advance!

Error

    const results = await db.user.findOne({where:{phoneNumber: body.phoneNumber}})
                                  ^

TypeError: Cannot read properties of undefined (reading 'findOne')
    at login (C:\Users\Ali\Desktop\Learning\Mafia-api\user\user.service.js:5:35)
    at Layer.handle [as handle_request] (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\layer.js:95:5)
    at next (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\route.js:144:13)
    at Route.dispatch (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\route.js:114:3)
    at Layer.handle [as handle_request] (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\layer.js:95:5)
    at C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\index.js:284:15
    at Function.process_params (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\index.js:346:12)
    at next (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\index.js:280:10)
    at Function.handle (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\index.js:175:3)
    at router (C:\Users\Ali\Desktop\Learning\Mafia-api\node_modules\express\lib\router\index.js:47:12)
[nodemon] app crashed - waiting for file changes before starting...

Model: user.js

    module.exports = async (sequelize, DataTypes) => {
    const user = await sequelize.define('users', {
        id: {
            type: DataTypes.INTEGER,
            allowNull: false,
            autoIncrement: true,
            primaryKey: true,
        },

        phoneNumber: {
            type: DataTypes.STRING(20),
            allowNull: false,
            unique: true
        },

        displayName: {
            type: DataTypes.STRING,
            allowNull: false,
            unique: true
        },

        xp: {
            type: DataTypes.INTEGER,
            allowNull: false
        },

        gender: {
            type: DataTypes.ENUM,
            allowNull: false,
            values: ['Male', 'Female']
        },

        currentAvatar: {
            type: DataTypes.STRING,
            allowNull: false,
        },

        createdAt: {
            type: DataTypes.DATE,
            allowNull: false
        }
    })

    user.association = model => {
        user.hasMany(model.currencyWallet);

        user.hasMany(model.userSetting);

        user.hasMany(model.soldMarketStoreItem);

        user.hasMany(model.soldGameStoreItem);

        user.hasMany(model.gamePlayerInformation);

        user.hasMany(model.report, {
            as: 'user'  
        });

        user.hasMany(model.report, {
            as: 'targetUser'
        });
    }
    return user
}

Service: user.service.js

const db = require('../models');

async function login(req, res) {
    const body = req.body;
    const results = await db.user.findOne({where:{phoneNumber: body.phoneNumber}})
    res.json({
        success: 0,
        message: 'Results found!'
    })
    res.json({
        success: 0,
        message: 'ERROR'
    })
}

module.exports = {
    login
}

Index.js

const express = require('express');
const app = express();
const userRouter = require('./user/user.router');
const PORT = 5000 
const HOST = 'localhost'
const db = require('./models');

app.use(express.json());

app.use('/', userRouter);

db.sequelize.sync().then(() => {
    app.listen(PORT, () => console.log(`Server running on http://${HOST}:${PORT}`));
})

config.json

  "development": {
    "username": "root",
    "password": null,
    "database": "mafia",
    "host": "127.0.0.1",
    "dialect": "mysql"
  }

CodePudding user response:

findOne is deprecated in the latest version of [email protected]

https://github.com/mongodb/node-mongodb-native/blob/2.0/lib/collection.js

You can use this query instead

find(query).limit(1).next(function(err, doc){
   // handle data
})

CodePudding user response:

In Model: user.js you are definign the model as users

But in user.service.js you're calling the model as user

Change this line in User model

...

 const user = await sequelize.define('users', 

...

To this line

const user = await sequelize.define('user',... // should be user, not users

Hope it'll fix your problem.

  • Related