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

Dynamic React Gallery with Interactive Image Picker

Looking to develop a new photo management application as an alternative to Google Photos, with a focus on displaying and selecting images in a user-friendly way. Currently using the react-grid-gallery library for this purpose. Here is my current implement ...

Google Cloud Platform (GCP) reported a Stripe webhook error stating that no matching signatures were found for the expected signature

Current Stripe version: "8.107.0" I am encountering an issue with Stripe webhook verification whenever I deploy my webhook on Google Cloud Platform (GCP). Despite trying various methods to include the raw body in the signature, including the cod ...

Establishing a connection to SQL Server through the use of Express.js

Having some issues with my code to establish a connection to SQL Server from express.js. I'm trying to handle errors by assigning them to a global variable and returning it at the end of the function, but for some reason the value is always undefined. ...

Encountering a cluster error with Node.js everyauth

Currently, I am developing a scalable application using node.js and encountering an issue. Whenever I click on the Facebook authentication link (/auth/facebook) and get redirected back, it throws the following error: {"error":{"message":"redirect_uri is ...

Heroku's Node Express experiencing unexpected spikes in service response time

My Node application on Heroku is experiencing sporadic spikes in service times, sometimes reaching over 20000ms when it should be around 50ms. These spikes occur during static file loads and a simple API call that provides a heartbeat connection to active ...

Is there cause for worry regarding the efficiency issues of utilizing Object.setPrototypeOf for subclassing Error?

My curiosity is piqued by the Object.setPrototypeOf(this, new.target.prototype) function and the cautionary note from MDN: Warning: Modifying an object's [[Prototype]] is currently a slow operation in all browsers due to how modern JavaScript engines ...

Combining React, Express, and Nodemailer poses challenges in rendering components and sending emails simultaneously

Looking to utilize client-side routing for my React app and also incorporate Nodemailer for sending emails. However, since Nodemailer cannot be used on the client-side, I need to implement it on the Express server. Here is how the server code looks like: ...

Make sure to call super.onDestroy() in the child component before overriding it

I find myself with a collection of components that share similar lifecycle logic, so I decided to create a base component that implements the OnDestroy interface. abstract class BaseComponent implements OnDestroy { subscriptions = new Array<Subscript ...

Retrieving the location.host parameter within NgModule

I am currently working on integrating Angular Adal for authenticating my application's admin interface with Azure AD. However, I have encountered a challenge with the redirectUri setting. My goal is to dynamically retrieve the current app's host ...

troubleshooting angular universal with HTTPS

My angular universal app is all set up and running smoothly for POST requests on the server-side using localhost to pre-render my app. An example of a working URL would be http://localhost:8000/api/get-info. However, things took a turn when I deployed the ...

Tips for creating Material UI elements using React and Typescript

I am looking to extend a component from the Material UI library by creating a custom component that encapsulates specific styles, such as for a modal wrapper. However, I feel that my current solution involving the props interface may not be ideal. Is the ...

Creating Typescript packages that allow users to import the dist folder by using the package name

I am currently working on a TypeScript package that includes declarations to be imported and utilized by users. However, I have encountered an issue where upon publishing the package, it cannot be imported using the standard @scope/package-name format. I ...

Utilizing Express, Request, and Node.js to manage GET requests in typescript

I'm struggling with using Express and Request in my project. Despite my efforts, the response body always returns as "undefined" when I try to get JSON data from the server. In my server.js file, this is the code snippet I have been working on: impo ...

Loading an Angular2 app is made possible by ensuring that it is only initiated when a DOM element is detected

In my main.ts file, the code below is functioning perfectly: import { platformBrowserDynamic } from '@angular/platform-browser-dynamic'; import { AppModule } from './app.module'; platformBrowserDynamic().bootstrapModule(AppModule); H ...

Animate in Angular using transform without requiring absolute positioning after the animation is completed

Attempting to incorporate some fancy animations into my project, but running into layout issues when using position: absolute for the animation with transform. export function SlideLeft() { return trigger('slideLeft', [ state('void&a ...

Make sure to update both npm and express.js to the latest version available

After installing the latest version of node.js on my machine, I found that my npm version is 1.4.28 and express version is 2.5.8. I attempted to update Express using the command: npm update express -g Unfortunately, this did not work as expected. Is the ...

Packaging an NPM module to enable unique import paths for Vite and Typescript integration

Is there a way to package my NPM module so that I can use different import paths for various components within the package? I have looked into webpack solutions, but I am working with Vite and TypeScript. This is the structure of my package: - src - ato ...

React App's proxy configuration to connect with an Express server for PassportJS authentication is currently malfunctioning

After spending some time trying to configure a proxy for my React app to connect with my Express backend, using passportjs for Google social authentication, I encountered an issue. The React development server is running on PORT 3000 while the Express ser ...

Exploring the concept of the never type in TypeScript 2

Exploring the latest features in TypeScript 2.0, I came across the never type. It appears to be a clever method for defining the type of functions that do not have a return value. If I understand correctly, the never type can be assigned to any other type ...

Tips for Simplifying Complex Switch Cases with Object Literals in TypeScript

I have a unique situation where I need to switch between two functions within an object literal. One function takes two numerical arguments, "A" and "B", while the other function only takes a single string argument, "C". My TypeScript code showcases my di ...