sequelize : cannot seed association values in DB table

拈花ヽ惹草 提交于 2019-12-12 18:15:14

问题


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: 'someone@somewhere.com',
            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..


回答1:


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: 'sameer',
            lastName: 'manek',
            email: 'sameermanek@hotmail.com',
            password: bcrypt.hashSync('poochies', 8),
            type: 'admin',
            createdAt: new Date(),
            updatedAt: new Date()
        }], {});

        const user = await User.findOne({
            where: {
                type: 'admin',
                email: 'sameermanek@hotmail.com'
            },
        });

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



回答2:


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', [{ // ...



回答3:


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: 'someone@somewhere.com',
            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, {});
    }
};


来源:https://stackoverflow.com/questions/52227663/sequelize-cannot-seed-association-values-in-db-table

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!