Issue
New to Node and Typescript. I am getting an error that mongoose.connect is not a function when I run tsc.
I have the following code:
import express = require('express');
import * as mongoose from "mongoose";
/** Routes for the app */
import apiUserRouter from "./api/user"
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'));
}
}
If I change
import * as mongoose from "mongoose"
to
import mongoose = require('mongoose');
Then everything works fine.
I have run the following npm command for types as my understanding is that this should have fixed the issue.
npm install @types/mongoose --save
Edit: Adding my packages.json
{
"name": "nodejs-ts-test2",
"version": "1.0.0",
"description": "",
"main": "index.js",
"scripts": {
"test": "echo \"Error: no test specified\" && exit 1"
},
"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"
}
}
and tsconfig.json:
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"outDir": "dist",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
Solution
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"));
}
}
Answered By - Akshar Patel
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.