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

Modifying the menu with Angular 4 using the loggedInMethod

Struggling to find a solution to this issue, I've spent hours searching online without success. The challenge at hand involves updating the menu item in my navigation bar template to display either "login" or "logout" based on the user's current ...

Activate TypeScript EMCAScript 6 support for Cordova projects in Visual Studio

I am interested in utilizing the async/await feature of TypeScript in my VS2015 Cordova project. I have updated "target": "es6" in tsconfig.json Although there are no errors shown in intellisense, I encounter the following error while building the project ...

The database is causing Mongod to crash during queries

My AWS instance is set up with nodejs and mongod running. The collection I am attempting to query from contains around 289,248 documents. Below is the code snippet I am using to fetch my data: var collection = db.collection('my_collection'); co ...

Issue with Material UI v5: Uncaught TypeError - Unable to access properties of an undefined object (specifically 'create')

After setting up the ThemeSetting.tsx context, I encountered an issue where I could not utilize <Button><Button> and other components that rely on the theme from Material UI React.js in TypeScript: error TypeError: Cannot read properties of u ...

Leverage Webpack to bundle ES Modules with TypeScript module aliases

Hello there, I recently created an npm module using Typescript and ES-modules. Inside the /source folder, you can find my tsconfig.json file which includes a path alias. { "compilerOptions": { "moduleResolution": "Node ...

Theme customization in Material UI includes the addition of a custom color. However, this custom color is missing from the control values in Story

Currently in my project, I am utilizing a stack that includes React 18, TypeScript, MUI 5, and Storybook 6.5. I have been attempting to incorporate custom colors into my MUI Theme and have them reflect in Storybook's dropdown options for the color p ...

The geo element needs to be formatted as either an array or object, specifically denoted as type: "Point"

While attempting a POST request like the following "{ "imgUrl": "Server\Pictures\i14182109167", "text": "Myself in seoul", "tag": ["seoul", "tour"], "geometry" : {"type": "Point","coordinates": [80, -27]} }" An error occurred &a ...

Creating a TypeScript library with Webpack without bundling may seem like a daunting task, but

Currently, I am developing a React component package using Typescript and NPM. During my research, I discovered that generating individual .js and .d.ts files is more beneficial than bundling them into one bundle.js file. However, I am facing difficulty in ...

Exploring async componentDidMount testing using Jest and Enzyme with React

angular:12.4.0 mocha: "8.1.2" puppeteer: 6.6.0 babel: 7.3.1 sample code: class Example extends Angular.Component<undefined,undefined>{ test:number; async componentWillMount() { this.test = 50; let jest = await import('jest&apos ...

Implementing conditional wildcard route redirection in an Angular routing module

Is there a way to manage redirect routes when users enter the wrong URL using wildcards controlled by conditions? In my project, I have 3 main modules that are separate, and each of them has specific conditions for user access based on roles. The issue I ...

What is the best way to modify an object within a pure function in JavaScript?

Currently, I am exploring different strategies to ensure that a function remains pure while depending on object updates. Would creating a deep copy be the only solution? I understand that questions regarding object copying are quite common here. However, ...

I am having difficulty accessing the values stored in my cardTiles variable

I am facing an issue with a variable called cardTiles in my Angular 9 component. The variable is defined as cardTitles:Product[] = []; The Product class is defined as follows export class Product{ productName: string;} When I console.log(this.cardTi ...

Built-in Promises within MongoDB

Is there a way to determine which methods in mongoDb have an inbuilt promise? For example, "updateOne() , findOne()" have inbuilt promises that we can access using ".then", but many other mongoDB methods lack this feature. How can we identify which methods ...

The individual is currently tracking his own movements

When developing a function to handle user following and unfollowing, I encountered an issue where the code checking if a user can follow themselves was not functioning as expected. Despite implementing an if statement to prevent self-following, users were ...

Tips for crafting a WHERE ... OR ... query in Symfony2 using MongoDB:asyncio

In my UserRepository, I am looking to create custom queries similar to how I can do with $dm->createQuery('some query') in non-MongoDB scenarios. Is there a way for me to achieve this? I noticed that the method $this->createQueryBuilder() ...

Is there a way for me to conduct multiple counts and choose the highest one especially if they are all promises?

Here is my voting controller for a post. If the user has not already voted on the post (their voterId is not in the votes array), their vote is added by adding their voterId to the votes array of the post. The voteCount is then reset to the length of that ...

Tips on getting the dropdown value to show up on the header when it changes using Angular 2 and TypeScript

I need assistance with creating a dropdown field in Angular2. When the user selects "car", I want it to display beside the heading. Can anyone provide guidance on how to achieve this? HTML: <h1>Heading <span *ngFor= "let apps of apps">({{apps ...

Exploring the depths of object properties with Angular, JavaScript, and TypeScript: A recursive journey

Let's consider an object that looks like this: const person = { id: 1, name: 'Emily', age: 28, family: { mother: { id: 101, name: 'Diana', age: 55 }, fathe ...

What is the process for configuring React on one server and springboot on a separate server?

Can you help me with the setup of the following: Web Server : I need to set up a react + typescript application using npm at Backend Server : I also need to configure a Springboot backend server at I am currently using webpack to build the react applica ...

Cease the generation of dynamically produced sounds

I am encountering an issue in Angular where I am unable to stop playing an audio from a service. Below is my play() method: play(item: string): void { const audio = new Audio(); audio.src = item; audio.load(); audio.play(); } In order to stop all ...