The issue arose as a result of a SQLITE_ERROR, specifically mentioning that the Users table does not exist. However, the model has been

Greetings! I am currently facing an issue while trying to integrate the "sequelize-typescript" library into my Express.JS REST API that I developed using Dependency Injection. The error I am encountering is:

SQLite Error: no such table: Users

Below is the code snippet for my "user.ts" entity:

export class User extends Model {
@PrimaryKey
@Column({
    type: DataType.INTEGER,
    autoIncrement: true
})
declare userId: number

@Column({
    type: DataType.STRING
})
declare firstName : string;

@Column({
    type: DataType.STRING
})
declare lastName: string;

@Column({
    type: DataType.STRING
})
declare email: string;

@Column({
    type: DataType.STRING
})
declare phone: string;}

Additionally, here is the middleware code for my database setup:

export default class DatabaseMiddleware {
private databaseInstance : Sequelize;

constructor() {
    this.databaseInstance = new Sequelize({
        database: process.env.MAMLAKHA_DATABASE_NAME,
        dialect: "sqlite",
        host: process.env.MAMLAKHA_DATABASE_HOST,
        username: process.env.MAMLAKHA_DATABASE_USERNAME,
        password: process.env.MAMLAKHA_DATABASE_PASSWORD,
        // storage: process.env.MAMLAKHA_DATABASE_STORAGE_PATH,
        logging(sql, timing) {
            console.log("The SQL statement from Sequelize executed is", sql, timing);
        },
        models: [User],
        repositoryMode: true
    });
}

public async connectToDatabase() {
    try {
        await this.databaseInstance.authenticate();
        if(process.env.ENVIRONMENT_PROFILE === "development") {
            await this.databaseInstance.sync({ alter: true });
        }

        console.log("Connection to database has been established successfully");
    } catch(error) {
        console.error("Unable to connect to database due to", error);
    }
}

public getDatabaseInstance() {
    return this.databaseInstance;
}}

Lastly, here is the initialization code for the entire REST API:

class App {
private baseDirectory : string;
private expressApp : Express

// Middleware Instances
private databaseMiddleware : DatabaseMiddleware;

constructor() {
    dotenv.config({ path: "./.env.development" });
    this.baseDirectory = __dirname;
    this.expressApp = express();
    routingContainer(Container);

    useExpressServer(this.expressApp, {
        routePrefix: process.env.MAMLAKHA_ROUTE_PREFIX,
        defaultErrorHandler: false,
        controllers: [this.baseDirectory + `/**/controllers/*.ts`]
    });

    this.expressApp.use(bodyParser.urlencoded({ extended: false }));
    this.expressApp.use(bodyParser.json());

    this.databaseMiddleware = new DatabaseMiddleware();
}

run() {
    this.expressApp.listen(process.env.MAMLAKHA_REST_API_PORT, () => {
        console.info(`Hello there, it's Mamlakha app and it's running on port ${process.env.MAMLAKHA_REST_API_PORT} 🤘`);
    });

    this.databaseMiddleware.connectToDatabase();
}

get expressAppInstance : Express {
    return this.expressApp;
} } const main : App = new App(); main.run();

I have attempted to resolve the issue following the Github documentation for the library, but unfortunately, I am unable to make it work. If you have encountered this issue before, I would greatly appreciate any solutions you can provide. Thank you!

Answer â„–1

Upon initial inspection, it appears that there may be an issue with your grasp of Sequelize.

Have you taken the necessary steps to create a migration and execute it on the database instance?

To create a migration using the sequelize CLI, please refer to the following link: https://sequelize.org/docs/v6/other-topics/migrations/#creating-the-first-model-and-migration

To run the migration using the sequelize CLI, you can follow the guidelines outlined in this link: https://sequelize.org/docs/v6/other-topics/migrations/#running-migrations

Answer â„–2

Appreciate the time taken to address the question and big thanks to @RobertRendell for providing a solution that helped me. I managed to find 2 solutions that resolved the error I was facing. One of them was the answer by @RobertRendell, which suggests creating the table before running the application.

Another solution involves adding

sync({ alter: true, force: true });
to your Sequelize instance. By setting the force: true flag, the table will be created based on your data model if it does not already exist in your database.

Once again, special thanks to @RobertRendell for sharing his solution, and I hope that my experience can help others facing a similar issue.

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Optimal location for data validation using mongoose and express

Is there a clear answer on where to handle data validation in an express.js and mongoose setup? I currently use a combination of methods but it's becoming cumbersome. What is the best practice: Utilizing the Model (mongoose) Utilizing the Controller ...

The object is not a valid function

Within this class object, I have an instance of a class that I am unable to call its functions within. Despite the IDE allowing me to call the getPoistionDiagram function: export class NodeW { childrenIds: string[]; diagram?: { coordinates: { ...

Can anyone provide guidance on setting up a TypeScript service worker in Vue 3 using the vite-plugin-pwa extension?

I am looking to develop a single-page application that can be accessed offline. To achieve this, I have decided to implement a PWA Service Worker in my Vue webapp using TypeScript and Workbox. I found useful examples and guidance on how to do this at . Ho ...

Establish a connection between MongoStore and a database, while also authenticating with the admin credentials

How can a MongoStore be initialized to connect to a database and authenticate with the "admin" one? Can it be achieved similar to this using mongoose: var db = mongoose.createConnection('mongodb://myname:mypwd@localhost:27017/mydb', { auth: { a ...

Exploring the directory structure of static files using Node.js/express

I have configured my express server to serve static files from the public directory: app.use(express.static(__dirname + '/public')); Within the public directory, there is an images folder: /public/images This images folder contains a variety ...

Typescript or Angular 2 for Google Maps

Is there a way to integrate Google Maps Javascript API with Typescript or Angular 2? Although libraries like https://github.com/SebastianM/angular2-google-maps are available, they may not provide full support for features like Events and Places Libraries ...

The union type consisting of String, Boolean, and Number in type-graphql has encountered an error

I attempted to create a union type in type-graphql that represents the String, Number, and Boolean classes, but unfortunately, it was not successful. Does anyone have any suggestions on how to achieve this? export const NonObjectType = createUnionType({ ...

"Exploring the world of Typescript declarations and the CommonJS module

I'm encountering confusion while creating declaration files (d.ts). For instance, I have developed an NPM package called "a" with a single CommonJS module index.ts: export interface IPoint { x: number; y: number; } export default function s ...

Creating a document in Mongoose and setting an Index

In my application's frontend, users can input their work experience in a small form and add more fields dynamically to include additional work experiences. If you're unsure of what I mean, check out this GIF. Before sending the form data to the ...

Ensure that the interface limits the key value to match precisely the value of a constant in Typescript

Seeking assistance in understanding how to enforce a specific type for an optional key within an interface: const FIRST = "FIRST" const SECOND = "SECOND" interface TSomeInterface { element: Element order?: typeof FIRST | typeof ...

Exploring views with Node.js and Express static middleware routing

I've been searching for a solution to what seems like a simple question, but haven't had any luck. Currently, I am using express with ejs as my template engine and my directory structure looks like this: |-static |---css |---img |---js |-v ...

Using middleware in Express to handle GET requests

Can the request object sent to any route be accessed globally in Express, without having to explicitly access it in a .get method or similar? ...

Obtain the unformatted query generated by the sequelize.js library

Hello there, everyone! I'm currently working on a node.js/express project with sequelize.js connected to PostgreSQL. Here's my dilemma: I'm looking for a way to store the raw queries created by sequelize in a log history, but I haven't ...

Saving JSON format in VueX State Management

I'm relatively new to using Vue/VueX and I am exploring methods for storing JSON data in the VueX state. Initially, it seemed like a simple task: state { jsonthing: { ... } } However, I encountered an issue where getters return an Observer type ins ...

Error: An unexpected symbol '<' was encountered after the build process in Vue.js

I just finished deploying a MEVN stack application to heroku. While everything is functioning properly locally, I am encountering a blank page and the following errors in the console post-deployment: Uncaught SyntaxError: Unexpected token '<' ...

Secure Your Passwords with Encryption in NestJS using @nestjs/mongoose before saving them

Seeking to encrypt passwords before saving using @nestjs/mongoose. Came across examples written in pseudocode like this: UsersSchema.pre('save', (next: any) => { if (!this.isModified('password')) return next(); this.password = en ...

When exporting a custom ES6 module and importing it into a different local project, you may encounter unexpected outputs such as being undefined or

Currently, I am using TypeScript 3.4.5 and Webpack 4.32.2 on Windows 10 via WSL. My goal is to create a local package of tools that consolidates basic classes into an index file for exporting. However, when I try to import these classes into other project ...

Having issues with using the class selector in SVG.select() method of the svg.js library when working with TypeScript

Exploring the capabilities of the svg.js library with typescript has presented some challenges when it comes to utilizing CSS selectors. My goal is to select an SVG element using the select() method with a class selector. In this interactive example, this ...

Angular - Ensuring correct rendering of a subcomponent with input parameter on the first update

Here is a snippet of code showcasing a list of educations and a component: <cdk-virtual-scroll-viewport itemSize="5" class="list-scroll"> <app-education-item *ngFor="let education of loadedEducations" ...

Configuring rows in React datagrid

I am working on a component where I receive data from the backend and attempt to populate a DataGrid with it. Below is the code for this component: export const CompaniesHouseContainer: React.FC<Props> = () => { const classes = useStyl ...