Error: Model function not defined as a constructor in TypeScript, mongoose, and express

Can anyone help me with this error message "TypeError: PartyModel is not a constructor"?
I've tried some solutions, but now I'm getting another error as well.
After using const { ... } = require("./model/..."), I'm seeing "TypeError: Cannot read properties of undefined (reading 'findOne')"

app.ts

import express, { Request, Response } from "express";

const cors = require("cors")
import mongoose from "mongoose"
const configModel = require("./model/ConfigSchema")
const PartyModel = require("./model/PartySchema")

const app = express()

...

app.post('/createParty', cors(), async function (req: CustomRequest<partyModelInterface>, res: Response) {
    const input = req.body

    const today = new Date()

    await reloadConfig()

    const party = new PartyModel({
        id: partyNumber,
        game: input.game,
        master: input.master,
        description: input.description,
        players: input.players,
        time: today
    })

    partyNumber++

    saveToDb(party)

    res.send("A party has been created")
})

PartySchema.ts


import mongoose from "mongoose";

const partySchema = new mongoose.Schema({
    id: {
        type: Number,
        required: true,
        unique: true
    },
    game: {
        type: String,
        required: true,
    },
    master: {
        type: String,
        required: true
    },
    description: {
        type: String,
        required: true
    },
    players: {
        type: Number,
        required: true
    },
    time: {
        type: Date,
        required: true
    }
}, {
    versionKey: false,
    collection: 'parties'
})

module.exports =  mongoose.model('Party', partySchema)

Answer №1

Consider utilizing the Model.create() function to generate a database model, similar to the example below:

const event = await EventModel.create({
        id: eventNumber,
        type: input.type,
        organizer: input.organizer,
        description: input.description,
        attendees: input.attendees,
        date: today
    });

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

The latest entries are not visible on Mongoose unless the page is refreshed

There is a router with handlers for GET and POST requests related to documents. When creating new documents and posting them, the redirection works smoothly. However, upon initial page load after creation, only existing documents are displayed. It's o ...

Encountered a network error: A rogue token < was found in JSON at position 0 within a new Apollo

https://i.sstatic.net/D25ai.png const httpLink = createHttpLink({ uri: 'http://localhost:3090/' }) const client = new ApolloClient({ link: httpLink, cache: new InMemoryCache() }) client.query({ query: gql` query users { ...

Unveiling RxJs: The secret to extracting the notifier value using the takeuntil operator

I have a straightforward Rxjs timer set up that runs until a notifier emits a signal, it's pretty basic so far. enum TimerResult = { COMPLETE, ABORTED, SKIPPED }; _notifier: Subject<TimerResult> = new Subject(); notifier$: Observab ...

Troubles with Jest tests are encountered when using ts-jest in an ES2020/ESNEXT TypeScript project

Currently, I am working on a VueJS project that utilizes ViteJS for transpilation, which is functioning properly. However, when Jest testing is involved alongside ts-jest, the following Jest configuration is used: jest.config.ts import { resolve } from &q ...

Can a promise-based test run automatically when testing Express with Mocha?

I have been facing a puzzling situation with my test files. When I have only 'test1.js' present, Mocha reports that there are no tests passing, giving me a "0 passing" message. However, if both 'test1.js' and 'test2.js' are pr ...

Error TS6200 and Error TS2403: There is a conflict between the definitions of the following identifiers in this file and another file

Currently working on setting up a TypeScript node project and running into issues with two files: node_modules@types\mongoose\index.d.ts node_modules\mongoose\index.d.ts Encountering conflicts in the following identifiers when trying ...

What is the best way to integrate the Telegram login widget into an Angular application?

Does anyone know how I can integrate the Telegram login widget into my Angular application without resorting to hacks? The required script is as follows: <script async src="https://telegram.org/js/telegram-widget.js?5" data-telegram-login="bot_name" ...

Mastering the latest NavigationStart feature in @angular-router version 3.0.0-alpha.*

I've noticed some interesting new events within the updated Angular 2 Router. There's NavigationStart, NavigationEnd, and NavigationFailed (or something similar). Is there anyone who has successfully implemented these events? I've tried a ...

Sails.js navigating through sessions

What is a rolling session in Sails.js? A rolling session is a session that expires after a set amount of time without user activity, except for websockets live updating data. If the user navigates to a different part of the site before the session expires, ...

Challenge with Node.js Express Route Authorization

I'm currently facing an issue with retrieving audio/image files from the database. app.use(restrictMiddleware()); Due to restrictions imposed by the Route Restrict feature, the retrieval process is not functioning as expected. Are there any alternati ...

Extending the Express Request Interface in Typescript to Include Additional Properties

In order to enhance the Express Request interface with a new property called "context" for middleware purposes, I am trying to achieve the following: const myMiddleware = (req: Request, res: Response, next: NextFunction) => { req.context.something = ...

Encountering an Express.js HTTP 500 ERROR when using res.send("Some text"); is working on the page, however, the error occurs when trying to use res.render('file');

My website has a page located at /request that features a form. The form's method is POST and the action leads to /request. In the POST handler in request.js, the intention is to take action with the form data, like storing it in a database, and then ...

"During a loop, the command '$push' in mongoose adds an empty

Having trouble handling a POST request that needs to add information to multiple documents using $push, but it seems to be pushing an empty object. However, $set is working perfectly fine. I've tried using for loops, Q library, and async library, but ...

What are the best ways to enhance change detection efficiency in Angular?

One issue I am facing involves two components and a service. It appears that when moving from the view of a routed component to elements in different components like a matMenu and an input field, the routed component seems to refresh itself. This becomes p ...

Solving Typing Problems in React TypeScript with "mui-icons" Props

I have a small compost project with only an App.JSX file that is functioning perfectly, but now I need to convert it to App.TSX. After changing the extension to .TSX, I encountered two errors that I'm unsure how to resolve. function MyComponentWithI ...

Unable to establish a connection with mongo-atlas

I am facing an issue while setting up a connection with mongo-atlas as it is returning a connection error Below is the code I'm using: const mongoose = require('mongoose') const connectionString = 'mongodb+srv://<username>:<p ...

Adding to an existing array in SQLite by updating a column using Sequelize

My code includes a model definition for saving product data using Sequelize: This is how the Product model looks: import {Optional, Model, Sequelize, DataTypes } from 'sequelize'; /*This is the Product model used to save the data about products* ...

Display a page as Ajax eagerly waits for a reply

I'm currently working on an express project that utilizes ejs as a view engine and AJAX for front-end http calls. When I make a POST request like this: $.ajax({ type: 'POST', data: {'username' : $('#username').va ...

"Retrieve a list of all routes that have been registered in Node.js

I am trying to retrieve a list of all registered routes in my project. Here is the code I have used for this purpose: const app = require("express"); let routers = app._router.stack .filter((r) => r.route) .map((r) => { return { ...

ideas on integrating a text messaging application in the MEAN stack

Currently, I am utilizing a third-party SMS service provider which is adding extra costs to my services. I am now looking to develop my own SMS gateway application using MEAN stack technologies. After extensive research, I have not been able to find prop ...