Encountering TypeError during build on Next.js functions integrated with Mongoose

Encountering TypeError in the next build when trying to call model functions for methods and/or statics from pages/api.

The error message tends to mention either property does not exist or expression is not callable.

I have followed Mongoose Typescript recommendations.

import { Model, Schema, models, model } from 'mongoose';
import { User } from 'types/user';

interface UserModel extends Model<User> {
    findAuthenticated(hash: string): Promise<User>;
    getProfile(): Promise<User>;
}

const userSchema = new Schema<User, UserModel>({...});
...
export default models.User || model<User,UserModel>('User', userSchema);

Using Next.js 13 with Mongoose 6.8.2 and typescript 4.9.4.

Answer №1

Implementing a versatile helper function for typing the model.

// models/user.ts
...
export default createModel<User,UserModel>('User', userSchema);

// utils/mongoose.ts
import { Model, Schema, models, model } from 'mongoose';

export function createModel<T, TModel = Model<T>>(
    modelName: string,
    schema: Schema<T>
): TModel {
    const mongooseModel = models[modelName] || model<T, TModel>(modelName, schema);
    return mongooseModel as TModel;
}

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 overflowing issue with the Nextjs Tailwind Marquee Component is causing a display

I've recently developed a unique nextjs/tailwind component. This component displays an isometric marquee that scrolls horizontally. However, I'm facing an issue where the content overflows to the right and causes the page to become horizontally s ...

Encountering problem when attempting to incorporate fade in/fade out effect animation

I have a webpage that features multiple buttons, each triggering a fade-in/fade-out animation when clicked. This animation also involves changing the contents of a specific div. Though everything is functioning properly, there is a brief moment (about hal ...

populate a data list with information sourced in Angular 8

I am looking to populate this model oldDataSource: Array<any> = []; with the values from the datasource. This is the code I have tried: ngOnInit(): void { this.dataSourceInit(); } dataSourceInit(): void { this.dataSource = new DefaultScore ...

What is the best way to retrieve specific values from an ng-bootstrap modal?

I am working on a website that includes an ng-bootstrap modal. This modal contains two <select> elements with dynamic items, allowing the user to click on two buttons. One button simply closes the modal and sets the value of the Reactive Form to new ...

Navigating between pages has become challenging due to issues with the navbar, sidebar,

I successfully developed 4 Angular components: 1st component: menu 2nd component: header 3rd component: home 4th component: login The menu component features a sidebar/navbar created using Material UI. The login component consists of the login page. Howe ...

I'm encountering an error stating that a property does not exist for Twilio.Response() while attempting to convert a Twilio CORS Node.js example to TypeScript. Can anyone shed

In my current project, I am converting a CORS Node.js example from Twilio's documentation into TypeScript. Here is the original Node.js code: exports.handler = (context, event, callback) => { const client = context.getTwilioClient(); const resp ...

How can I fix the error 'unable to locate import statement outside of a module' in Next.js?

I recently started using Next.js and integrated Jest with Babel for unit testing. After running npm test, I encountered the following error related to 'import': FAIL tests/pages/index.test.js ● Test suite failed to run Jest encountered an unex ...

What is the most secure method to define options and retrieve their values in a type-safe manner?

I am currently utilizing a library that offers an interface with a great deal of flexibility. type Option = number | { x?: number; y?: number; z?: number; } interface Options { a?: Option; b?: Option; c?: Option; d?: Option; } function init ...

Angular 5 is throwing an error stating that it cannot read the property 'text' of undefined

I have developed a question component where I have added some predefined questions. However, when I attempt to execute the application, it displays 'undefined' text. Below is my component code: import { Component, OnInit } from '@angular/c ...

Using modules imported from external directories in typescript

My project structure is as follows: workspace |- thegame |- node_modules | package.json | bs-config.json |- src | tsconfig.json |- app | game.model.ts (<-- I want to import game-engine here) |- game-engine |- dist (generated after local bu ...

Why isn't my Promise fulfilling its purpose?

Having trouble with promises, I believe I grasp the concept but it's not functioning as expected in my project. Here is a snippet of my code : (I am working with TypeScript using Angular 2 and Ionic 2) ngOnInit() { Promise.resolve(this.loadStatut ...

Importing a form input as a constant in an API endpoint script

Recently stepping into the realm of React, I'm encountering difficulties in my Next.js app related to imports and exports. My goal is to export a const from a form component to an API endpoint for use within a function. While I can see the form compo ...

"findOneAndUpdate may update the database, but it also suffers from

Situation: My async function successfully updates the database but then fails to proceed with the remaining script. //Handle the data once retrieved... async function burnStatus(data) { console.log("Burn Data Compilation in Progress..."); let filter ...

What is the proper way to define an `async` functional component in React?

Can someone help me figure out why my image won't load in TypeScript? Below is the code I'm using: import "./styles.css"; import React, { FC } from "react"; type ImageLoad = (subString: string) => Promise<boolean>; ...

Type validation in TypeScript through cross-referencing variables

Can TypeScript be used to define a variable that determines the type of other variables? I want to simplify the process by only needing to check one variable, stateIndicator, which is dependent on other variables to infer their types. type A = {prop1: st ...

"Incorporating an onChange event handler to an input field in a React

I'm currently facing a challenge with my input box component as I aim to implement a script that will restrict all inputs except for numbers. function onChangeHandler(e: React.ChangeEvent) { this.value.replace(/(?![0-9])./gmi,''); } expo ...

What is the best way to add .xlsx and .docx files to the Typescript compilation output?

For my server, I have decided to use Typescript with NodeJS. One of the challenges I encountered in my server logic is manipulating .xlsx and .docx files. Unfortunately, these file types are not included in the Typescript compilation output. These specifi ...

Searching for documents with a specific key within a nested object using Mongoose in Node.js

Here is how my current MongoDB structure looks like: Room: { // ... other data users : { userId1 : { // other user info ... } userId2 : { // other user info ... } } } Now, I am looking to create a Mongoose query that will help me ...

The value being passed as a parameter is a number, which cannot be assigned to a parameter expecting a Date type

I'm currently in the process of testing a function by passing a date as a parameter, but I seem to be encountering an issue that I can't quite figure out. When structured like this, it throws an error stating "Argument of type 'number' ...

Error message: "An issue has been encountered within Angular 4 where it is

Thank you for any assistance, I realize this may be a beginner question... but I seem to be missing something and my TypeScript code is error-free. My goal is simple: I want to track which Main Menu Item is currently selected. To achieve this, I have bou ...