Mongoose Import for TypeScript Doesn't Work
Since you didn't share your package.json or tsconfig, it was not possible to say where the error might be. So I created new project for the code you have shared such that the error does not occur. Compare the files that I am sharing with the ones you have to narrow down your problem.
The package.json
{
"name": "mong_type",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"keywords": [],
"author": "",
"license": "ISC",
"devDependencies": {
"@types/express": "^4.11.1",
"@types/mongoose": "^5.0.3",
"typescript": "^2.7.2"
},
"dependencies": {
"express": "^4.16.2",
"mongoose": "^5.0.7"
}
}
tsconfig.json
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"outDir": "./dist",
"strict": true,
"allowSyntheticDefaultImports": true,
"esModuleInterop": true
},
"include": ["src"]
}
src/app.ts
import express from "express";
import mongoose from "mongoose";
class App {
public express: express.Application;
constructor() {
this.express = express();
this.setupDb();
}
private setupDb(): void {
var mongoDb = "mongodb://127.0.0.1/my_database";
mongoose.connect(mongoDb);
var db = mongoose.connection;
db.on("error", console.error.bind(console, "MongoDB Connection error"));
}
}
This:
import mongoose from 'mongoose'
worked for me after running:
npm install mongoose @types/mongoose --save
Way more detailed explanation on why this works, here.