Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

findByPrimary is not a function

TL;DR

I am getting an error saying that findByPrimary is not a function when using Sequelize.

I have been following this tutorial on how to make a currency system for a Discord bot using Sequelize and SQLite 3. However, whenever I use findByPrimary on a model I get the following error:

(node:9182) UnhandledPromiseRejectionWarning: TypeError: Users.findByPrimary is not a function

Users is defined in models/Users.js:

module.exports = (sequelize, DataTypes) => {
    return sequelize.define('users', {
        userId: {
            type: DataTypes.STRING,
            primaryKey: true
        },
        balance: {
            type: DataTypes.INTEGER,
            defaultValue: 0,
            allowNull: false
        }
    }, {
        timestamps: false
    });
};

which is referred to in dbObjects.js:

//modules
const Sequelize = require('sequelize');

//sequelize connection info
const sequelize = new Sequelize('database', 'username', 'password', {
    host: 'localhost',
    dialect: 'sqlite',
    logging: false,
    storage: 'database.sqlite'
});

//models
const Users = sequelize.import('models/Users');

//export
module.exports = {Users};

which is imported in server.js and used as one of the arguments in execute in a command file:

const {Users} = require('./dbObjects');

//command is a file (in this case commands/inventory.js and commands/buy.js)
command.execute(message, Users);

which is used in the commands that don't work:
commands/inventory.js

module.exports = {
    execute: async (message, Users) => {
        const target = message.mentions.users.first() || message.author;
        const user = await Users.findByPrimary(target.id);
    }
};

commands/buy.js

module.exports = {
    execute: async (message, Users) => {
        const user = await Users.findByPrimary(message.author.id);
    }
};

I have tried using findById but that results in the same error message. I also have tried adding the following code to the execute function in the command files:

const Sequelize = require('sequelize);
const SQLite = require('sqlite3');

The only difference between my code and the aforementioned tutorial's is that I am using a command handler.

All other Sequelize functions such as findAll have been working.

like image 411
cherryblossom Avatar asked Aug 23 '26 14:08

cherryblossom


1 Answers

Please Use findByPk instead of findByPrimary See sequelize documents : http://docs.sequelizejs.com/manual/models-usage.html

Users.findByPk(id)
like image 187
Riajul Islam Avatar answered Aug 25 '26 06:08

Riajul Islam



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!