MangoDB Compass 无法使用 TypeORM 连接到我的后端。

huangapple go评论79阅读模式
英文:

MangoDB Compass can not connect to my backend using TypeORM

问题

我试图创建一个简单的Web应用程序,在其中可以在React Web应用程序上从MongoDB数据库中显示用户。但是,我在使用TypeORM和我的MongoDB数据库时遇到了问题。实际上,我的后端存储库无法访问数据库。

以下是我的package.json文件:

{
  "name": "backend",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "dev": "nodemon index.ts",
    "start": "node ./dist/index.js",
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
    "migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection  --name ",
    "migration:run": "npm run typeorm -- migration:run"
  },
  "license": "UNLICENSED",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "mongodb": "^3.6.0",
    "typeorm": "^0.3.11"
  },
  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.14",
    "@types/mongodb": "^4.0.7",
    "@types/node": "^18.11.8",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "typescript": "^4.8.4"
  }
}

以下是我的connectionService.ts文件,用于创建到数据库的连接:

import { DataSource, DataSourceOptions } from "typeorm";
import { Utilisateurs } from "../entities/utilisateurs";

class connectionServices {
    public myDataSource: DataSource;

    constructor(dbConfig: DataSourceOptions) {
        this.myDataSource = new DataSource(dbConfig)
    }
    public async getUsers() {
        const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
        const data = await myusers.find({});
        console.log(data);
        return data;
    }
}

export default (connectionServices);

以下是我的index.ts文件:

import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";

function main() {

    const app = express();
    const service = new connectionServices({
        type: "mongodb",
        url: "mongodb://localhost:27017",
        port: 27017,
        database: "users",
        synchronize: true,
        entities: [
            "src/entities/**/*.ts"
        ],
    });

    app.use(cors())

    app.get('/users/:id', function (req, res, next) {
        res.json({ msg: 'This is CORS-enabled for all origins!' })
    })

    app.listen(80, function () {
        console.log('CORS-enabled web server listening on port 80')
    })

    app.get('/', (req, res) => {
        res.send('Well done!');
    })

    app.listen(4321, () => {
        console.log('The application is listening on port 4321!');
    })

    app.get('/users', (req, res) => {
        res.send(service.getUsers());
    })

}

main();

最后,这是我的ormconfig.json文件:

{ 
   "type": "mongodb", 
   "host": "localhost",
   "url": "mongodb://localhost:27017",
   "port": 27017, 
   "database": "test", 
   "synchronize": true, 
   "logging": false, 
   "entities": [ 
      "src/entity/**/*.ts" 
   ], 
   "migrations": [ "src/migration/**/*.ts" 
   ], 
   "subscribers": [ "src/subscriber/**/*.ts" 
   ], 
   "cli": { 
      "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber" 
   } 
}

后端构建并正常启动。但是,当我在URL中输入http://localhost:4321/users时,在我的终端中会出现此错误,并且后端会崩溃。

我尝试过将数据库的URL或将参数"host": "localhost"与正确的端口一起放入,但都没有起作用。

我已经查看了几个教程和视频,但都没有成功...如果有人看到我的问题的解决方案,那将是很好的!

英文:

I am trying to create a simple web application where I can diplay users from a MongoDB database on a React web application.
However I am stuck on a problem with TypeORM and my MongoDB database. Indeed, my backend repository can not access to the database.

Here is my package.json file :

{
  "name": "backend",
  "version": "1.0.0",
  "main": "index.js",
  "scripts": {
    "build": "tsc",
    "dev": "nodemon index.ts",
    "start": "node ./dist/index.js",
    "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
    "migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection  --name ",
    "migration:run": "npm run typeorm -- migration:run"
  },
  "license": "UNLICENSED",
  "dependencies": {
    "cors": "^2.8.5",
    "dotenv": "^16.0.3",
    "express": "^4.18.2",
    "mongodb": "^3.6.0",
    "typeorm": "^0.3.11"
  },
  "devDependencies": {
    "@types/cors": "^2.8.13",
    "@types/express": "^4.17.14",
    "@types/mongodb": "^4.0.7",
    "@types/node": "^18.11.8",
    "nodemon": "^2.0.20",
    "ts-node": "^10.9.1",
    "typescript": "^4.8.4"
  }
}

Here is my connectionService.ts file, which is supposed to create the connection to the database :

import { DataSource, DataSourceOptions } from "typeorm"
import { Utilisateurs } from "../entities/utilisateurs";

class connectionServices{
    public myDataSource:DataSource;


    constructor(dbConfig: DataSourceOptions){
        this.myDataSource = new DataSource(dbConfig)
    }
    public async getUsers (){
        const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
        const data = await myusers.find({});
        console.log (data);
        return data;
      }
}

export default (connectionServices);

Here is my index.ts file :

import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";


function main() {
 
const app = express();
const service = new connectionServices({
  type: "mongodb",
  url: "mongodb://localhost:27017",
  port: 27017,
  database: "users",
  synchronize: true,
  entities: [ 
    "src/entities/**/*.ts" 
 ],
});

app.use(cors())
 
app.get('/users/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

app.get('/', (req, res) => {
    res.send('Well done!');
})

app.listen(4321, () => {
    console.log('The application is listening on port 4321!');
})

app.get('/users', (req,res) => {
    res.send(service.getUsers());
})

}

main();

And finally here is my ormconfig.json file :

{ 
   "type": "mongodb", 
   "host": "localhost",
   "url": "mongodb://localhost:27017",
   "port": 27017, 
   "database": "test", 
   "synchronize": true, 
   "logging": false, 
   "entities": [ 
      "src/entity/**/*.ts" 
   ], 
   "migrations": [ "src/migration/**/*.ts" 
   ], 
   "subscribers": [ "src/subscriber/**/*.ts" 
   ], 
   "cli": { 
      "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber" 
   } 
}

The backend builds and launches properly :
MangoDB Compass 无法使用 TypeORM 连接到我的后端。

However when I type in the url http://localhost:4321/users, I get this error in my terminal and the backend crashes :
MangoDB Compass 无法使用 TypeORM 连接到我的后端。

I have tried to put the url of the data base, or put the parameter "host": "localhost" with the correct port but nothing worked.

I have looked on several tutorials, videos without success...
If someone sees the solution to my problem that would be great!

答案1

得分: 0

你没有提供你的实体。然而,我认为问题发生是因为typeorm找不到你的实体。

尝试将src/entity/**/*.ts更改为src/entity/**/*{.ts,.js}

如果需要的话,对迁移和订阅者也做同样的事情。

英文:

You didn't provide your entities. however, I think the problem occurred because typeorm couldn't find your entities.

try changing src/entity/**/*.ts to src/entity/**/*{.ts,.js}.

Do the same thing for migration and subscribers if needed.

答案2

得分: 0

以下是翻译好的部分:

事实上,问题出现在 index.ts 文件和 connectionService.ts 文件中。

在服务文件中,缺少了一个用于连接到数据库的函数:

import { createConnection, DataSource, DataSourceOptions } from "typeorm";
import { Utilisateurs } from "../entities/utilisateurs.entity";

class connectionServices {
    public myDataSource: DataSource;

    async connect() {
        await this.myDataSource.connect();
    }

    constructor(dbConfig: DataSourceOptions) {
        this.myDataSource = new DataSource(dbConfig);
    }
    public async getUsers() {
        const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
        const data = await myusers.find({});
        console.log(data);
        return data;
    }
}

export default connectionServices;

而在 index.ts 文件中,我调用的是包含日期的表的 promise,而不是数据。这是正常工作的文件:

import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";
import { Utilisateurs } from './entities/utilisateurs.entity';

async function main() {
  const app = express();
  const service = new connectionServices({
    type: "mongodb",
    host: "localhost",
    port: 27017,
    database: "users",
    synchronize: true,
    entities: [
      Utilisateurs
    ],
  });

  await service.connect();

  app.use(cors());

  app.get('/users/:id', function (req, res, next) {
    res.json({ msg: 'This is CORS-enabled for all origins!' });
  });

  app.listen(80, function () {
    console.log('CORS-enabled web server listening on port 80');
  });

  app.get('/', (req, res) => {
    res.send('Well done!');
  });

  app.listen(4321, () => {
    console.log('The application is listening on port 4321!');
  });

  app.get('/users', async (req, res) => {
    res.send(await service.getUsers());
  });
}

main();

经过这些修改,一切都正常工作。

英文:

In fact the problem was in the index.ts file and in the connectionService.ts file.

In the service, it was missing a function in order to connect to the data base :

import { createConnection, DataSource, DataSourceOptions } from "typeorm"
import { Utilisateurs } from "../entities/utilisateurs.entity";

class connectionServices{
    public myDataSource:DataSource;

    async connect(){
        await this.myDataSource.connect();
    }

    constructor(dbConfig: DataSourceOptions){
        this.myDataSource = new DataSource(dbConfig);
    }
    public async getUsers (){
        const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
        const data = await myusers.find({});
        console.log (data);
        return data;
      }
}

export default (connectionServices);

And in the index.ts file, I was calling the promise of a table containing the date, and not the data. Here is the working file :

import express from 'express';
import cors from 'cors';
import connectionServices from "./service/connectionService";
import { Utilisateurs } from './entities/utilisateurs.entity';


async function main() {
const app = express();
const service = new connectionServices({
  type: "mongodb",
  host: "localhost",
  port: 27017,
  database: "users",
  synchronize: true,
  entities: [ 
    Utilisateurs
 ],
});

await service.connect();

app.use(cors())
 
app.get('/users/:id', function (req, res, next) {
  res.json({msg: 'This is CORS-enabled for all origins!'})
})
 
app.listen(80, function () {
  console.log('CORS-enabled web server listening on port 80')
})

app.get('/', (req, res) => {
    res.send('Well done!');
})

app.listen(4321, () => {
    console.log('The application is listening on port 4321!');
})

app.get('/users', async(req,res) => {
    res.send(await service.getUsers());
})

}

main();

With these modifications, everything works properly.

huangapple
  • 本文由 发表于 2023年1月3日 17:40:15
  • 转载请务必保留本文链接:https://go.coder-hub.com/74991494.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定