簡體   English   中英

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

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

我有一個 Group.js、Task.js model 和一個 db.js 文件。 組有許多任務。

當我運行服務器時,我收到錯誤 TypeError: group.addTask is not a function。

以下是文件:

任務.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;
}

數據庫.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;

這就是我從 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);
        });
    });
}

有誰知道是什么導致了這個錯誤?

TypeError: group.addTask is not a function表示結果記錄中沒有 addTask 屬性,或者如果 addTask 屬性存在但它的類型不是 function

你可以做類型檢查

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