Reputation: 4650
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
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
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
Reputation: 1979
There are total 2 syntex we can use here.
const mongoose = require('mongoose');
then use mongoose.connect
import * as mongoose from `mongoose`;
then use mongoose.connect
import {connect} from `mongoose`;
then use connect directly
Upvotes: 8
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