Node和Typescript的新功能。我在运行tsc时收到mongoose.connect不是函数的错误。
我有以下代码:
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'));
}
}
如果我改变
import * as mongoose from "mongoose"
至
import mongoose = require('mongoose');
然后一切正常。
我已经对类型运行了以下npm命令,因为我的理解是这应该已经解决了该问题。
npm install @types/mongoose --save
编辑:添加我的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"
}
}
和tsconfig.json:
{
"compilerOptions": {
"target": "es2015",
"module": "commonjs",
"outDir": "dist",
"strict": true,
"noImplicitAny": false,
"esModuleInterop": true,
"allowSyntheticDefaultImports": true
}
}
由于您没有共享package.json或tsconfig,因此无法说出错误可能在哪里。因此,我为您共享的代码创建了一个新项目,这样就不会发生错误。将我共享的文件与您必须缩小问题范围的文件进行比较。
该的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"));
}
}
本文收集自互联网,转载请注明来源。
如有侵权,请联系 [email protected] 删除。
我来说两句