Using TypeScript with Node.js: the module is declaring a component locally, but it is not being exported

Within my nodeJS application, I have organized a models and seeders folder. One of the files within this structure is address.model.ts where I have defined the following schema:


export {};
const mongoose = require('mongoose');

const addressSchema = new mongoose.Schema({
  street: {
    type: String,
    required: true,
  },
  number: {
    type: String,
    required: true,
  },
  city: {
    type: String,
    required: true,
  },
  codePostal: { type: mongoose.Schema.Types.ObjectId, ref: 'codePostal'  },
  country: {
    type: String,
    required: true,
  },
  longitude: {
    type: Number,
    required: false,
  },
  latitude: {
    type: Number,
    required: false,
  }
});

const ALLOWED_FIELDS = ['id', 'street', 'number','city', 'codePostal', 'country'];


/**
 * @typedef Address
 */
const Address = mongoose.model('Address', addressSchema);
Address.ALLOWED_FIELDS = ALLOWED_FIELDS;
module.exports = Address;

Additionally, I have a file named addresses.ts for seeding data with the following content:

import faker from 'faker'
import {
  Address
} from '../src/api/models/address.model'

export const seedAdresses = async () => {
  try {
    const quantity = 10
    const adresses = []

    for (let i = 0; i < quantity; i++) {
      adresses.push(
        new Address({
          street   : faker.address.streetName(),
          number   : faker.address.streetAddress(),
          city     : faker.address.city(),
          country  : faker.address.country(),
          longitude: faker.address.longitude(),
          latitude : faker.address.latitude(),

        })
      )
    }

  } catch (err) {
    console.log(err);
  }
}

seedAdresses()

However, when attempting to import Address, I encountered an error stating:

The module '"../src/api/models/address.model"' declares 'Address' locally, but it is not exported. I am confused as to why it is not exported even though 'module.exports = Address;' exists in my schema!

Answer №1

An issue arises from mixing CommonJS exports with ES6 imports/exports. To resolve this, utilize export { Address }; in address.model.ts instead of export {};.

Furthermore, it is advisable to employ

import { Schema, model } from "mongoose"
for consistency with ES6 standards.

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

Encountered a Node Express Post 500 error (Internal Server Error) triggered by jquery-3.4.1.min.js

Recently, I've been immersed in developing a node js/express js application for quite some time. Most of my get's and post's are functioning properly when triggered from jquery $ajax calls. However, there seems to be an issue with one speci ...

Steps for eliminating a selection in the dropdown list:

I am dealing with a situation in which my select element gets new options added based on a specific input value. However, each time the value is changed, more options are appended to the select element instead of replacing the old ones. How can I remove th ...

In the world of Typescript, object-based type inference reigns

I'm grappling with TypeScript to correctly deduce typing in the given code snippet: type Customer = { name: string } type Item = { price: number } const customerConfig = { action: () => [{name: 'Alice'}] as Customer[], } const item ...

Error: JSON parsing error - Unexpected token at the start of the JSON data when using JSON.parse() function

Backend code router.route('http://localhost:5007/api/media') .post(mediaCtrl.saveMedia) async saveMedia(req, res) { let file = req.files.file let ext = req.body.extension let path = req.body.path if(_.isNull(file) || _.isEmp ...

Encountering a CORS error while utilizing a Node.js Express API with an Angular frontend

While developing an API using Node.js, Express, and MongoDB, I encountered a CORS error when trying to call the API from an Angular application. Strangely enough, the API works fine when deployed on Render, but throws an error locally. Error: Access to XM ...

Ways to Resolve the "TS2533: Object May Be Either 'Null' or 'Undefined'" Error on a Dynamic Object

I'm encountering an issue with the following code snippet: interface Schema$CommonEventObject { formInputs?: { [key: string]: Schema$Inputs; } | null; } interface Schema$Inputs { stringInputs?: Schema$StringInp ...

developing TypeScript classes in individual files and integrating them into Angular 2 components

We are currently putting together a new App using Angular2 and typescript. Is there a more organized method for defining all the classes and interfaces in separate files and then referencing them within angular2 components? import {Component, OnInit, Pi ...

Enhance the app.get response by integrating data fetched from an http.get request

Currently, I am utilizing express and passing the path as a URL parameter. app.get("/download", function (req, res) { var location; var options = { host: 'example.com', port: 80, path: req.query.url.replace(/ /g, ...

Connecting a Database with NestJS and TypeORM: A step-by-step guide to establish a connection with TypeORM and ensure easy access to

Could someone please explain how to create a DB instance using TypeORM? I want it to be accessible like this service, but the Connection class is deprecated. import { Inject, Injectable } from '@nestjs/common'; import { Connection, Repository } ...

A step-by-step guide on converting a JSON object to a CSV file using the json2csv nodejs module

I'm in the process of learning how to convert a JSON object into a CSV file using the json2csv node module. This is completely new to me as I have not worked with JSON previously. The structure of my JSON object is as follows: { "car": { ...

Node.JS Logic for Scraping and Extracting Time from Text

Currently, I am working on developing a web scraper to gather information about local events from various sites. One of my challenges is extracting event times as they are inputted in different formats by different sources. I'm seeking advice on how t ...

The response of the Typescript Subscription function

I'm struggling with retrieving the subscribe array in NG2. Being new to typescript, I find it difficult to understand how to pass variables between functions and constructors. This is what my code currently looks like: export class RosterPage exten ...

When trying to run Puppeteer JavaScript on a page in headless mode, the execution fails

My webpage (secretpage.php) has JavaScript in the HTTP response that sends the value of the userName parameter to my server. <svg/onload=fetch('http://localhost:8080/username='+document.getElementById("userName").innerHTML)> When ...

What causes React JS to continuously render in an infinite loop when using hooks and useState

I am struggling with updating the current state of my component based on a result using a custom hook in React. Whenever I try to update it, I end up in an infinite loop rendering due to my usage of the useState() hook. I am still new to working with Rea ...

Is it possible for remote Node.js applications to communicate in real-time using full-duplex messaging via WebSockets

With no human involvement, both Endpoint A and Endpoint B are standalone Node.js applications operating independently. Endpoint A is tasked with establishing a secure web socket connection with Endpoint B and ensuring it remains active 24/7. Each endpoin ...

Expanding the typings for an established component in DefinitelyTyped

Is there a way to define new typings for additional props in DefinitelyTyped? After updating the material-ui library with some new props for the SelectField component, I realized that the typings in DefinitelyTyped are outdated. Is it possible to extend th ...

The data in my MySQL table is not appearing on an Angular Material table when using Node.js

HTML file content <table mat-table [dataSource]="dataSource" class="mat-elevation-z8"> <ng-container matColumnDef="id"> <th mat-header-cell *matHeaderCellDef> No. </th> <td mat-cell *matCellDef="let element"> {{ele ...

Authentication Error: PassportJS Method not Found

Encountering a problem while trying to access passport functions from a separate config file. It seems like passport is not exposed when the file is required in routes. The error occurs at .post(passportConfig.authenticate('local-login', { Error ...

Error occurs when using Express.js in combination with linting

https://www.youtube.com/watch?v=Fa4cRMaTDUI I am currently following a tutorial and attempting to replicate everything the author is doing. At 19:00 into the video, he sets up a project using vue.js and express.js. He begins by creating a folder named &apo ...

Angular auto-suggest components in material design

Can someone assist me in resolving my issue? I am trying to incorporate an autocomplete feature with a filter into my form. .ts file : contactArray; selectedContact: IContact; myControl = new FormControl(); filteredContact: Observable<string[] ...