简体   繁体   中英

Sequelize, Javascript TypeError: group.addTask is not a function

I have a Group.js, Task.js model and a db.js file. Group has many Tasks.

When I run the server I get the error TypeError: group.addTask is not a function.

Here are the files:

Task.js

const Sequelize = require("sequelize");

module.exports = function(sequelize,DataTypes){
    const Task = sequelize.define('Task',{
        name: Sequelize.STRING
    })
    return Task;
}

Group.js

const Sequelize = require("sequelize");

module.exports = function(sequelize,DataTypes){
    const Grupa = sequelize.define('Grupa',{
        naziv: Sequelize.STRING
    })
    return Grupa;
}

db.js

const Sequelize = require("sequelize");
const sequelize = new Sequelize("spiralatest","root","password",{host:"127.0.0.1",dialect:"mysql"});
const db = {};

db.Sequelize = Sequelize;
db.sequelize = sequelize;

db.task = require("./models/Task.js")(sequelize);
db.group = require("./models/Group.js")(sequelize);

db.group.hasMany(db.task);

module.exports=db;

And this is what I call from index.js which causes the error above:

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

db.sequelize.sync({ force: true }).then(function () {
    initialize();
    console.log("Tables created and test data set-up");
});

function initialize() {
    db.task.findOrCreate({ where: { name: 'task1' } });
    db.group.findOrCreate({ where: { name: 'group1' } }).then(function (group) {
        db.task.findOne().then(function (x) {
            group.addTask(x);
        });
    });
}

Does anyone know what causes this error?

TypeError: group.addTask is not a function means in result record there is no addTask property or if addTask property is there but it's type is not function

you can do type checking

if (group.addTask && typeof group.addTask === 'function'){
      group.addTask(x);
}
function initialize() {
    db.task.findOrCreate({ where: { name: 'task1' } });
    db.group.findOrCreate({ where: { name: 'group1' } }).then(function (group) {
        db.task.findOne().then(function (x) {
            if (group.addTask && typeof group.addTask === 'function'){
                  group.addTask(x);
            }
        });
    });
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM