Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
1.4k views
in Technique[技术] by (71.8m points)

javascript - Unhandled rejection TypeError: Role.Create is not a function error

I have got stuck on a .create is not a function error when I am trying to repopulate my database when I restart nodemon. I have had this working previously and all the tables populated fine I keep getting flagged this error. I am using Node, Express, Sequelize and Postgres pgAdmin4.

I have read on similar topics that a ; in node can cause errors like this but i have tried a few things and still get the same error.

//const Sequelize = require('sequelize')
const express = require("express");
const bodyParser = require ("body-parser");
// const { Sequelize, Op, Model, DataTypes } = require("sequelize");
// import authRoute from './server/routes/auth.routes';
// import postRoutes from './server/routes/diveLog.routes';
const cors = require("cors");

// creates an en express app
const app = express();

// set origin to 5002
// var corsOptions = {
//    origin: "http://localhost:5002"
//}
 // add bp and cors using api.use method

// parse requests of content type app/json
// app.use(cors(corsOptions));

app.use((req, res, next) => {
    res.header('Access-Control-Allow-Origin', '*');
    res.header(
        'Access-Control-Allow-Headers',
        'Origin, X-Requested-With, Content-Type, Accept',
    );
    next();
});

// parse requests of content-type
app.use(bodyParser.json());

//bp used to process form data as json
app.use(bodyParser.urlencoded({ extended: true }));

//database
const db = require("./server/models");
//const sequelize = require("pg");
const Role = db.userRole;
//const DivingSchool = db.approvedDivingSchool;
const Current = db.currentLevel;
const DiveType = db.diveType;
const DiveRegion = db.diveRegion;
const Visibility = db.visibilityLevel;
const DiveAgency = db.diveAgency;
const Certifications = db.diveCertification;
const MarineType = db.marineType;

//const user = db.userLogin;

try {
    db.sequelize.authenticate();
    console.log('Connection made to the database made.');
    } catch (error) {
    console.error('unable to connect:', error);
}

// db.sequelize.sync();
// force: true will drop the table if it already exists
db.sequelize.sync({ force: false })
    .then(() => {
    console.log(`Drop and resync database with { force: true }`)
    initial()
});

// simple route
app.get('/', (req, res) => {
    res.json({ message: "connected to the sustainable scuba database." });
});

// routes
require('./server/routes/auth.routes')(app);
require('./server/routes/user.routes')(app);
require('./server/routes/diveLog.routes')(app);
require('./server/routes/diveSchool.routes')(app);

// set port, listen for requests
const PORT = process.env.PORT || 5000;
app.listen(PORT, () => {
    console.log(`Server is now running on PORT ${PORT}.`);
});


function initial() {

     Role.create({
            userRoleID: 1,
            userRoleName: "User"
         });
         Role.create({
               userRoleID: 2,
               userRoleName: "School"
         });
         Role.create({
               userRoleID: 3,
               userRoleName: "SiteAdmin"
         });
         Role.create({
               userRoleID: 4,
               userRoleName: "SuperUser"
         });
}

Error message:

Unhandled rejection TypeError: Role.create is not a function

    at initial (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackendserver.js:86:11)

    at C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackendserver.js:63:5

    at tryCatcher (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_modulesluebirdjs
elea

seutil.js:16:23)

    at Promise._settlePromiseFromHandler (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_mo

dulesluebirdjs
eleasepromise.js:547:31)

    at Promise._settlePromise (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_moduleslueb

irdjs
eleasepromise.js:604:18)

    at Promise._settlePromise0 (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_moduleslue

birdjs
eleasepromise.js:649:10)

    at Promise._settlePromises (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_moduleslue

birdjs
eleasepromise.js:729:18)

    at _drainQueueStep (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_modulesluebirdjs

releaseasync.js:93:12)

    at _drainQueue (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_modulesluebirdjs
ele

aseasync.js:86:9)

    at Async._drainQueues (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulessequelize
ode_modulesluebird

js
eleaseasync.js:102:5)

    at Immediate.Async.drainQueues [as _onImmediate] (C:UsersJames GreeneWebstormProjectssoftwaredevprojectSustainableScubaackend
ode_modulesseque

lize
ode_modulesluebirdjs
eleaseasync.js:15:14)

    at processImmediate (internal/timers.js:439:21)

index.js

const config = require("../../config/db.config.js");

const Sequelize = require("sequelize");
const sequelize = new Sequelize(
      config.DB,
      config.USER,
      config.PASSWORD,

    {
      host: config.HOST,
      dialect: config.dialect,
      operatorsAliases: false,
        //logging: (...msg) => console.log(msg),

        pool: {
            max: config.pool.max,
            min: config.pool.min,
            acquire: config.pool.acquire,
            idle: config.pool.idle
        }
      }
     );

const db = {};

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

db.userLogin = require("./userLogin.model")(sequelize, Sequelize);
db.userRole = require("./userRole.model")(sequelize, Sequelize);
db.diveLog = require("./diveLog.model.js")(sequelize, Sequelize);
db.visibilityLevel = require("./visibility.model.js")(sequelize, Sequelize);
db.diveType = require("./diveType.model.js")(sequelize, Sequelize);
db.currentLevel = require("./currentLevel.model.js")(sequelize, Sequelize);
db.approvedDivingSchool = require("./approvedDivingSchool.model.js")(sequelize, Sequelize);
db.diveRegion = require("./diveRegion.model.js")(sequelize, Sequelize);
db.diveAgency = require("./diveAgency.model")(sequelize, Sequelize);
db.diveCertification = require("./diveCertifications.model")(sequelize, Sequelize);
db.marineLife = require("./marineLife.model")(sequelize, Sequelize);
db.diveSpot = require("./diveLog.model")(sequelize, Sequelize);
db.article = require("./articles.model")(sequelize, Sequelize);



/* db.userRole.belongsTo(db.userLogin, {
  through: "fk_userRoles",
  foreignKey: "userRoleID",
  otherKey: "userRole"
});
//db.userLogin.belongsTo(db.userRole, {
//  through: "fk_userRoles",
//  foreignKey: "userRole",
//  otherKey: "userRoleID"
//});
db.diveLog.belongsTo(db.visibilityLevel, {
    through: "fk_visibility",
    foreignKey: "diveVisibilityID",
    otherKey: "visibilityID"
});
//db.visibilityLevel.belongsTo(db.diveLog, {
//    through: "fk_visibility",
//    foreignKey: "visibilityID",
//    otherKey: "diveVisibilityID"
//});
db.diveLog.belongsTo(db.currentLevel, {
    through: "fk_current",
    foreignKey: "diveCurrentID",
    otherKey: "currentID"
});
db.currentLevel.belongsTo(db.diveLog, {
    through: "fk_visibility",
    foreignKey: "currentID",
    otherKey: "diveCurrentID"
});
db.diveLog.belongsTo(db.approvedDivingSchool, {
    through: "fk_divingSchool",
    foreignKey: "diveSchoolNameID",
    otherKey: "diveSchoolID"
});
db.approvedDivingSchool.belongsTo(db.diveLog, {
    through: "fk_divingSchool",
    foreignKey: "diveSchoolID",
    otherKey: "diveSchoolNameID"
});
db.diveLog.belongsTo(db.diveType, {
    through: "fk_diveType",
    foreignKey: "diveTypeID",
    otherKey: "diveTypeID"
});
db.diveType.belongsTo(db.diveLog, {
    through: "fk_diveType",
    foreignKey: "diveTypeID",
    otherKey: "diveTypeID"
});
db.diveLog.belongsTo(db.userLogin, {
    through: "fk_userID",
    foreignKey: "diverUserNumber",
    otherKey: "userID"
});
db.userLogin.belongsTo(db.diveLog, {
    through: "fk_userID",
    foreignKey: "userID",
    otherKey: "diverUserNumber"
});
db.approvedDivingSchool.belongsTo(db.diveLocation, {
    through: "fk_diveLocation",
    foreignKey: "diveSchoolLocation",
    otherKey: "diveLocationID"
});
db.diveLocation.belongsTo(db.approvedDivingSchool, {
    through: "fk_diveLocation",
    foreignKey: "diveLocationID",
    otherKey: "diveSchoolLocation"
});
 */

db.userRole = ["User", "School", "SiteAdmin", "SuperUser"];
db.diveType = ["Recreational", "Training", "Night Dive", "Deep Dive", "Drift", "Wreck", "Cave", "Reef", "Photo", "Research"];
db.VisibilityLevel = ["Bad < 5 m>", "Average 5-10 m", "Good 10-25 m", "Excellent > 25 m"];
db.currentLevel = ["Light > 1 knot", "Medium 1-2 knots", "Strong 2-3 knots", "Extreme > 2 knots"];
db.diveRegion = ["Europe", "North America", "South America", "Africa", "Oceania", "Asia"];
db.userLogin = ["Dummy", "dummy", "dummy@dummy.com", "Dummy", "Dummy"];
db.diveAgency = ["PADI", "SSI", "NAUI", "SDI"];
db.marineType = ["Cephalopods, crustaceans & other shellfish", "Corals and other invertebrates", "Marine mammals", "Ocean fishes", "Sea Turtles & Reptiles", "Sharks and Rays", "Marine Science and Ecosystems"];
db.diveCertification = ["Open Water", "Open Water Adv", "Open Water Instructor", "Divemaster", "Divemaster", "Freediver Basic", "Freediver Adv", "Freediver Instructor", "Freediver Master", "Dive Theory", "Digital Underwater Photographer", "Underwater Videographer", "Deep Diver", "Night Diver", "Ice Diver", "Cavern Diver", "Sus Scub Aware Campaign", "Sus Scub Aware Instructor", "Sus Scub Shark Conservation", "Dive Against Debris Speciality"];

module.exports = db;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)
等待大神答复

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...