【发布时间】:2020-01-16 13:52:10
【问题描述】:
我是 Node.js 的新手,正在尝试使用 TypeScript 构建一个 node/express/mongoose 服务器应用程序。
这是我的 app.ts 文件:
// 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;
但是,当我尝试编译我的应用程序时,我得到:
TypeError: mongoose.connect is not a function
我已经用光了我所有的 Google 技能——不走运。
谁能告诉我我做错了什么?
【问题讨论】:
-
将以下内容放在 mongoSetup 函数中,让我知道你得到了什么` mongoose.connect(this.mongoUrl, { useNewUrlParser: true, useUnifiedTopology: true }).then(function(data) { console.log("data = ", data); }).catch(function(err) { console.log(err); });`
-
在加载 mongoose 模块后记录你的 mongoose。
-
我刚刚复制了您的代码并将第一行替换为
import * as express from 'express';,它很简单。 -
@AlokDeshwal -- 感谢您的关注。我无法登录控制台,因为代码无法编译。另外,我用你所拥有的替换了我的 import 语句,我得到了相同的结果。没有改变任何东西。
-
我做了你的改变,做了一个
tsc ./lib/server.js并编译了。然后就跑了。感谢您的帮助。
标签: node.js mongodb typescript express mongoose