简体   繁体   English

续集,Javascript TypeError: group.addTask is not a function

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

I have a Group.js, Task.js model and a db.js file.我有一个 Group.js、Task.js model 和一个 db.js 文件。 Group has many Tasks.组有许多任务。

When I run the server I get the error TypeError: group.addTask is not a function.当我运行服务器时,我收到错误 TypeError: group.addTask is not a function。

Here are the files:以下是文件:

Task.js任务.js

const Sequelize = require("sequelize");

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

Group.js Group.js

const Sequelize = require("sequelize");

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

db.js数据库.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:这就是我从 index.js 中调用的导致上述错误的原因:

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 TypeError: group.addTask is not a function表示结果记录中没有 addTask 属性,或者如果 addTask 属性存在但它的类型不是 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);
            }
        });
    });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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