Mongoose在TypeScript中的导入无法使用。

22 浏览
0 Comments

Mongoose在TypeScript中的导入无法使用。

对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
    }
}

admin 更改状态以发布 2023年5月19日
0
0 Comments

这个代码:

import mongoose from 'mongoose'

在我运行之后起作用了:

npm install mongoose @types/mongoose --save

更详细的解释为什么可行,请参考这里

0
0 Comments

由于你没有分享你的 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"));
  }
}

0