Home > Software engineering >  How to Declare mongo models from different files with TypeScript
How to Declare mongo models from different files with TypeScript

Time:07-16

I have the following structure in my Node.js TypeScript project:

enter image description here

The important part here is the mongoModels. I have 2 models and they are connected as each Category model has field category.expertUserIds which contains 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 many project on exactly the same concept created as regular .js files but when I use TypeScript it is giving me this error:

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

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

Same is for Schema and for both files. So basically it counts that I declared already:

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

once and I cannot do it again for other file. How is that an error and how I can fix it as I am invoking Schema and model in different files?

CodePudding user response:

Actually I found solution. It was to replace:

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

with:

import { Schema, model } from "mongoose";

I don't know why TS didn't worked with "require".

CodePudding user response:

TypeScript basically runs on ESM(ECMAScript module) for Node. So you need to use import in place of const and require. TypeScript supports the EcmaScript module syntax which means you will be using modules in TypeScript using import and export keywords which is very convenient.

You can only import files ending with .ts and .d.ts extensions (as well as .js file). When you import these files using the import statement, they become modules.

  • Related