Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 321
Abana Clara Avatar asked Aug 07 '19 06:08

Abana Clara


Video Answer


1 Answers

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

like image 59
Binit Ghetiya Avatar answered Sep 21 '22 19:09

Binit Ghetiya