Abana Clara
Abana Clara

Reputation: 4650

Mongoose is undefined when using import syntax and not when using require

So I have my module written as such

import mongoose from 'mongoose';

export class MyModule {
   constructor(){
       //do
   }

   create(str){
      mongoose.connect(str); //cannot find property 'connect' of undefined
   }

}

When using the import syntax, I get the cannot find property 'connect' of undefined error; it works as intended when using require.

Weirdly enough, importing individual properties via import syntax works as intended,

import { connect } from 'mongoose'

but I need access to the entire ORM for some other reasons.

Why is it like so? Am I doing something wrong? To be fair, I don't have much experience in ES6 module system, TypeScript and Node.js so I might be missing something here.


I'm running this on Node.js with NestJS, on a typescript file.

Upvotes: 5

Views: 2989

Answers (4)

nerdy beast
nerdy beast

Reputation: 789

In your tsconfig.json file, you can set

"allowSyntheticDefaultImports": true,
"esModuleInterop": true

This will allow you to use the syntax

import mongoose from 'mongoose';

Upvotes: 4

Abana Clara
Abana Clara

Reputation: 4650

After installing @types/mongoose, VS Code reports that mongoose does not have a default export (all being named exports) that being the case, doing

import mongoose from `mongoose`

will not work. This also explains why getting individual properties instead works:

import { connect } from `mongoose`

As a workaround, thanks to @Binit Ghetiya who first mentioned it in this thread, you should do this instead:

import * as mongoose from `mongoose`

Which compiles every named export from Mongoose into the variable mongoose.

Upvotes: 2

Binit Ghetiya
Binit Ghetiya

Reputation: 1979

There are total 2 syntex we can use here.

ES15 (NodeJS)

const mongoose = require('mongoose');

then use mongoose.connect

ES16 (import/export)

import * as mongoose from `mongoose`;

then use mongoose.connect

or

import {connect} from `mongoose`;

then use connect directly

Upvotes: 8

huzaifamandviwala
huzaifamandviwala

Reputation: 435

Just change the import as follows:

import * as mongoose from 'mongoose';

Here is an example:

import * as mongoose from 'mongoose';

export class MyModule {

   constructor(){
       //do
   }

   create(str){
      mongoose.connect(str);
   }
}

Upvotes: 0

Related Questions