I am new to Node.js and am trying to build a node/express/mongoose server app with TypeScript.
Here is my app.ts file:
// lib/app.ts
import express from 'express';
import * as bodyParser from 'body-parser';
import { Routes } from './routes/crmRoutes';
import * as mongoose from "mongoose";
class App {
public app: express.Application;
public routePrv: Routes = new Routes();
public mongoUrl: string = 'mongodb://localhost/TodosDB';
constructor() {
this.app = express();
this.config();
this.routePrv.routes(this.app);
this.mongoSetup();
}
private mongoSetup(): void {
mongoose.connect(this.mongoUrl, {
useNewUrlParser: true,
useUnifiedTopology: true
});
}
private config(): void {
// support application/json type post data
this.app.use(bodyParser.json());
//support application/x-www-form-urlencoded post data
this.app.use(bodyParser.urlencoded({ extended: false }));
}
}
export default new App().app;
However, when I try to compile my application, I get:
TypeError: mongoose.connect is not a function
I've used up all my Google skill -- no luck.
Can anyone tell me what I'm doing wrong?
Mongoose lets you start using your models immediately, without waiting for mongoose to establish a connection to MongoDB. mongoose. connect('mongodb://localhost:27017/myapp'); const MyModel = mongoose. model('Test', new Schema({ name: String })); // Works MyModel.
You can require() and connect to a locally hosted database with mongoose. connect() , as shown below. You can get the default Connection object with mongoose.
Mongoose will try to connect with the MongoClient internally and return the instance of mongoose. this is the internal process of "conn. openUri" function and mongoose will execute the function. you can also connect the mongoClient directly without using mongoose.
connect() is use, whereas if there is multiple instance of connection mongoose. createConnection() is used. Hope someone can clarify more about this.
Replace:
import * as mongoose from "mongoose";
With:
import mongoose from "mongoose";
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With