A guide to declaring MongoDB models in TypeScript across multiple files

In my Node.js TypeScript project, the structure is as follows:

https://i.stack.imgur.com/YgFjd.png

The crucial part of the structure lies in mongoModels. I have 2 models where each Category model is connected and contains field category.expertUserIds which holds an array of user._id.

user.ts:

const { Schema, model } = require("mongoose");

const userSchema = new Schema({
  username: {
    type: String,
    require: true,
  },
  password: {
    type: String,
    require: true,
  },
});

module.exports = model("User", userSchema);

category.ts:

const { Schema, model } = require("mongoose");

const categorySchema = new Schema({
  name: {
    type: String,
    require: true,
  },
  description: {
    type: String,
  },
  expertUserIds: [
    {
      type: Schema.Types.ObjectId,
      ref: "User",
    },
  ],
});

module.exports = model("Category", categorySchema);

I have multiple projects based on the same concept created as regular .js files, but when using TypeScript, an error occurs:

mongoModels/category.ts:1:17 - error TS2451: Cannot redeclare block-scoped variable 'model'.

1 const { Schema, model } = require("mongoose"); ~~~~~

This issue also applies to Schema in both files. TypeScript considers that I have already declared:

const { Schema, model } = require("mongoose");

once and it cannot be done again for another file. How can this error be resolved since Schema and model are needed in different files?

Answer №1

After some digging, I discovered the solution. The key was to swap out:

const { Schema, model } = require("mongoose");

for:

import { Schema, model } from "mongoose";

I'm still puzzled as to why TypeScript didn't cooperate with "require".

Answer №2

TypeScript operates on ESM (ECMAScript module) for Node applications. This means that instead of using const and require, you will need to utilize the import keyword. In TypeScript, you can take advantage of EcmaScript module syntax by incorporating modules through the use of import and export keywords.

It is important to note that only files with extensions ending in .ts and .d.ts (as well as .js files) can be imported. By using the import statement, these files are transformed into modules within your TypeScript project.

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

Showing off the latest products at the top of the list

Typically, when utilizing ngFor, the most recent item is displayed underneath the initial element. For instance, a list containing: [Apple, Orange, Banana] If we use ngFor to display this list: Apple Orange Banana I am interested in learning a method t ...

Encapsulate the module function and modify its output

I am currently utilizing the node-i18n-iso-countries package and I need to customize the getNames function in order to accommodate a new country name that I wish to include. At the moment, I am achieving this by using an if-else statement like so: let cou ...

Error: Trying to modify an immutable property 'title' of object '#<Object>' - React JS and Typescript

Whenever I press the Add button, all input values are stored in a reducer. However, if I append any character to the existing value in the input fields, it triggers the following error: Cannot assign to read only property 'title' of object &apos ...

Transitioning a codebase from @angular-builders/custom-webpack to NX for project optimization

I need help migrating my Angular project from using "@angular-builders/custom-webpack" build targets to transitioning to an integrated NX monorepo. When I run the command npx nx@latest init --integrated, I receive the following warning: Unsupported build ...

Tips for utilizing Async/Await within an expressjs router

Having trouble with Async/Await in my Nodejs project. I'm a beginner with Nodejs and facing an issue connecting to my mongodb collection through my repository. When I integrate my controller with the repository, I end up getting a null response. Take ...

What is the best way to retrieve the most recent entry in a Firebase real-time database?

Utilizing Firebase's real-time database, I am updating values in a chart as they change. However, my struggle lies in retrieving only the most recent value added to the database. While browsing through limitToLast and 'child_added' do not w ...

Forwarding refs in React FC allows you to easily pass down

I have encountered an issue with references - I am trying to reference a function component and pass props to it. Currently, I have my Parent component and Child Component set up. In the parent component, I need to use a ref to access my child component. S ...

Unable to execute an Angular 2 application within Visual Studio 2015

I encountered an error while trying to set up an environment on VS 2015 with Angular2. Whenever I run the command "npm start," I receive the following error message. I attempted using "npm cache clean --force" before running "npm start," but the error pers ...

Steps for converting an Array of tuples into a Union of Tuples

I am attempting to develop a custom type that, when given an array of tuples as input, will generate the union of each index within the tuple. This may not be the most accurate terminology, but I hope you understand what I mean. const entries = [["name", ...

Is there a way to verify the existence of a user in mongoose?

Currently, I am attempting to verify the existence of a user with the code below: const userExist = await User.find({ username: req.body.username }); if (userExist) return res.status(400).send({ message: "User already exists" }); However, eve ...

Tips for avoiding the transmission of className and style attributes to React components

Hey there! I'm working on a custom button component that needs to accept all ButtonHTMLAttributes except for className and style to avoid any conflicts with styling. I'm using TypeScript with React, but I've run into some issues trying to ac ...

Creating a universal parent constructor that can take in an object with keys specific to each child class

I am looking to create a base class with a constructor that allows for all the keys of the child class to be passed. However, I am facing a challenge because 'this' is not available in constructors. Here is what I hope to accomplish: class BaseCl ...

How can I use TypeScript to wrap a component in Vue 3?

Looking to customize a PrimeVue component (Calendar) by styling it differently and then re-exporting it. Here's an example in React: const WrappedCalendar: React.FC<CalendarProps> = (props)=> <div style={{background:'green'}}&g ...

Encountering a Lint No Nested Ternary Error while utilizing the ternary operator

Is there a way to prevent the occurrence of the "no nested ternary" error in TypeScript? disablePortal options={ // eslint-disable-next-line no-nested-ternary units=== "mm&quo ...

Shifting successive elements in an array alternates

I have been working on a pick list component and have come up with the following layout https://i.stack.imgur.com/TnHAp.gif Whenever I try to move consecutive items, it keeps toggling between those two Here's a snippet of my code: moveDown(){ ...

What is the method for verifying the types of parameters in a function?

I possess two distinct interfaces interface Vehicle { // data about vehicle } interface Package { // data about package } A component within its props can receive either of them (and potentially more in the future), thus, I formulated a props interface l ...

What could be causing the countdown timer to speed up unexpectedly?

Currently, I am developing a quiz application. At the moment, I need to implement the following features: Countdown timer Questions Question Choices The countdown timer for each question functions properly as long as the answer button is not clicked or ...

Exploring the power of Vue CLI service in conjunction with TypeScript

I've recently set up a Vue project using the Vue CLI, but now I am looking to incorporate TypeScript into it. While exploring options, I came across this helpful guide. However, it suggests adding a Webpack configuration and replacing vue-cli-service ...

Update multiple fields of a document in Mongoose using the findAndUpdate method

I'm currently attempting to update various fields within a document: Game.findByIdAndUpdate(gameId, { $addToSet: { players: player.id }, $addToSet: { playersInfo: player }, function(err, model){...} } However, it see ...

Angular BreakPointObserver is a powerful tool that allows developers

Hey there! I've been working with the BreakpointObserver and have run into an issue while trying to define breakpoints for mobile and tablet devices. It seems that my code is functioning properly for tablets, but not for mobile devices. Upon further i ...