sameer manek
sameer manek

Reputation: 763

sequelize : cannot seed association values in DB table

I am trying to seed an association into my db using sequelize, the tables being: Users and Admins. For this I am relying on this answer on the forum. so here is my seed:

'use strict';
const bcrypt = require('bcryptjs')
module.exports = {
    up: async (queryInterface, Sequelize) => {
        queryInterface.bulkInsert('Users', [{
            firstName: 'someone',
            lastName: 'awesome',
            email: '[email protected]',
            password: bcrypt.hashSync('helloWorld', 8),
            type: 'admin',
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});

        const users = await queryInterface.sequelize.query(
            'SELECT id from Users;'
        );

        return await queryInterface.bulkInsert('Admins', [{
            id: users[0].id,
            phone: '+9999999999',
            status: true, createdAt: new Date(),
            updatedAt: new Date()
        }]);
    },
    down: async (queryInterface) => {
        await queryInterface.bulkDelete('Admins', null, {});
        await queryInterface.bulkDelete('Users', null, {});
    }
};

now, The data in user table is field up perfectly but the admin table remains empty

EDIT:

I tried to print out the users[0].id with the following code:

const users = await queryInterface.sequelize.query(
    "SELECT id from Users"
);

console.log(users[0].id)

the output was undefined

but the data was once again fed to the table! I know what is happening here, but don't know how to resolve!

P.S. I also added await for the very first method of the up, but this changed nothing..

Upvotes: 3

Views: 4057

Answers (4)

Ahmed Elazazy
Ahmed Elazazy

Reputation: 484

You can receive an array of the inserted objects and use it in the admin insertion.

let ids = await queryInterface.bulkInsert('Users', [{
                    firstName: 'someone',
                    lastName: 'awesome',
                    email: '[email protected]',
                    password: bcrypt.hashSync('helloWorld', 8),
                    type: 'admin',
                    createdAt: new Date(),
                    updatedAt: new Date()
                }], { returning: ['id'] });

let adminId = ids[0];

//Insert admin

Upvotes: 0

sameer manek
sameer manek

Reputation: 763

It took a while to figure this out, Thank you all.

literature I referred to: this question AND this part of official sequelize documentation

Here is the code that works:

'use strict';
const bcrypt = require('bcryptjs');
const models = require('../models');
const User = models.User;
module.exports = {
    up: async (queryInterface, Sequelize) => {
        queryInterface.bulkInsert('Users', [{
            firstName: 'aname',
            lastName: 'alastname',
            email: '[email protected]',
            password: bcrypt.hashSync('poochies', 8),
            type: 'admin',
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});

        const user = await User.findOne({
            where: {
                type: 'admin',
                email: '[email protected]'
            },
        });

        return await queryInterface.bulkInsert('Admins', [{
            id: user.id,
            phone: '+999999999999',
            status: true,
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});
    },
    down: async (queryInterface) => {
        await queryInterface.bulkDelete('Admins', null, {});
        await queryInterface.bulkDelete('Users', null, {});
    }
};

Upvotes: 5

Eugene Manuilov
Eugene Manuilov

Reputation: 4361

You need to add await to the first bulkInsert method call and save its results into userId variable. The bulkInsert promise is resolved with the first ID of inserted sequence, so you can use it to create an admin like this:

'use strict';
const bcrypt = require('bcryptjs');

module.exports = {
    up: async (queryInterface, Sequelize) => {
        const userId = await queryInterface.bulkInsert('Users', [{
            firstName: 'someone',
            lastName: 'awesome',
            email: '[email protected]',
            password: bcrypt.hashSync('helloWorld', 8),
            type: 'admin',
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});

        return queryInterface.bulkInsert('Admins', [{
            id: userId,
            phone: '+9999999999',
            status: true,
            createdAt: new Date(),
            updatedAt: new Date(),
        }]);
    },
    down: async (queryInterface) => {
        await queryInterface.bulkDelete('Admins', null, {});
        await queryInterface.bulkDelete('Users', null, {});
    }
};

Upvotes: 0

Aramil Rey
Aramil Rey

Reputation: 3475

You are not waiting for the users insert to end before querying for them, so this:

const users = await queryInterface.sequelize.query(
   'SELECT id from Users;'
);

Is empty, and this users[0].id must be throwing a type error

Adding an await to your first queryInterface.bulkInsert should fix that

await queryInterface.bulkInsert('Users', [{ // ...

Upvotes: 1

Related Questions