Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

nodeJS with ts : module declares component locally, but it is not exported

In my nodeJS app I have a models and seeders folder, I created an address.model.ts schema like that :


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;

and addresses.ts for seed like that :

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()

I got an error when import Address :

module '"../src/api/models/address.model"' declare 'Address' locally, but it is not exported. I don't understand why it's not exported although module.exports = Address; exist in my schema!

like image 382
sahnoun Avatar asked Jan 24 '23 23:01

sahnoun


1 Answers

The problem is that you are using CommonJS exports with ES6 imports/exports, use export { Address }; rather than export {}; in address.model.ts.

You should also consider using import { Schema, model } from "mongoose" to stay consistent with ES6.

like image 70
Elias Schablowski Avatar answered Apr 25 '23 16:04

Elias Schablowski