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

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

MangoDB Compass can not connect to my backend using TypeORM

问题

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

以下是我的package.json文件:

  1. {
  2. "name": "backend",
  3. "version": "1.0.0",
  4. "main": "index.js",
  5. "scripts": {
  6. "build": "tsc",
  7. "dev": "nodemon index.ts",
  8. "start": "node ./dist/index.js",
  9. "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
  10. "migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection --name ",
  11. "migration:run": "npm run typeorm -- migration:run"
  12. },
  13. "license": "UNLICENSED",
  14. "dependencies": {
  15. "cors": "^2.8.5",
  16. "dotenv": "^16.0.3",
  17. "express": "^4.18.2",
  18. "mongodb": "^3.6.0",
  19. "typeorm": "^0.3.11"
  20. },
  21. "devDependencies": {
  22. "@types/cors": "^2.8.13",
  23. "@types/express": "^4.17.14",
  24. "@types/mongodb": "^4.0.7",
  25. "@types/node": "^18.11.8",
  26. "nodemon": "^2.0.20",
  27. "ts-node": "^10.9.1",
  28. "typescript": "^4.8.4"
  29. }
  30. }

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

  1. import { DataSource, DataSourceOptions } from "typeorm";
  2. import { Utilisateurs } from "../entities/utilisateurs";
  3. class connectionServices {
  4. public myDataSource: DataSource;
  5. constructor(dbConfig: DataSourceOptions) {
  6. this.myDataSource = new DataSource(dbConfig)
  7. }
  8. public async getUsers() {
  9. const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
  10. const data = await myusers.find({});
  11. console.log(data);
  12. return data;
  13. }
  14. }
  15. export default (connectionServices);

以下是我的index.ts文件:

  1. import express from 'express';
  2. import cors from 'cors';
  3. import connectionServices from "./service/connectionService";
  4. function main() {
  5. const app = express();
  6. const service = new connectionServices({
  7. type: "mongodb",
  8. url: "mongodb://localhost:27017",
  9. port: 27017,
  10. database: "users",
  11. synchronize: true,
  12. entities: [
  13. "src/entities/**/*.ts"
  14. ],
  15. });
  16. app.use(cors())
  17. app.get('/users/:id', function (req, res, next) {
  18. res.json({ msg: 'This is CORS-enabled for all origins!' })
  19. })
  20. app.listen(80, function () {
  21. console.log('CORS-enabled web server listening on port 80')
  22. })
  23. app.get('/', (req, res) => {
  24. res.send('Well done!');
  25. })
  26. app.listen(4321, () => {
  27. console.log('The application is listening on port 4321!');
  28. })
  29. app.get('/users', (req, res) => {
  30. res.send(service.getUsers());
  31. })
  32. }
  33. main();

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

  1. {
  2. "type": "mongodb",
  3. "host": "localhost",
  4. "url": "mongodb://localhost:27017",
  5. "port": 27017,
  6. "database": "test",
  7. "synchronize": true,
  8. "logging": false,
  9. "entities": [
  10. "src/entity/**/*.ts"
  11. ],
  12. "migrations": [ "src/migration/**/*.ts"
  13. ],
  14. "subscribers": [ "src/subscriber/**/*.ts"
  15. ],
  16. "cli": {
  17. "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber"
  18. }
  19. }

后端构建并正常启动。但是,当我在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 :

  1. {
  2. "name": "backend",
  3. "version": "1.0.0",
  4. "main": "index.js",
  5. "scripts": {
  6. "build": "tsc",
  7. "dev": "nodemon index.ts",
  8. "start": "node ./dist/index.js",
  9. "typeorm": "ts-node -r tsconfig-paths/register ./node_modules/.bin/typeorm",
  10. "migration:generate": "npm run typeorm -- migration:generate --config src/config/ormconfig.json --connection --name ",
  11. "migration:run": "npm run typeorm -- migration:run"
  12. },
  13. "license": "UNLICENSED",
  14. "dependencies": {
  15. "cors": "^2.8.5",
  16. "dotenv": "^16.0.3",
  17. "express": "^4.18.2",
  18. "mongodb": "^3.6.0",
  19. "typeorm": "^0.3.11"
  20. },
  21. "devDependencies": {
  22. "@types/cors": "^2.8.13",
  23. "@types/express": "^4.17.14",
  24. "@types/mongodb": "^4.0.7",
  25. "@types/node": "^18.11.8",
  26. "nodemon": "^2.0.20",
  27. "ts-node": "^10.9.1",
  28. "typescript": "^4.8.4"
  29. }
  30. }

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

  1. import { DataSource, DataSourceOptions } from "typeorm"
  2. import { Utilisateurs } from "../entities/utilisateurs";
  3. class connectionServices{
  4. public myDataSource:DataSource;
  5. constructor(dbConfig: DataSourceOptions){
  6. this.myDataSource = new DataSource(dbConfig)
  7. }
  8. public async getUsers (){
  9. const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
  10. const data = await myusers.find({});
  11. console.log (data);
  12. return data;
  13. }
  14. }
  15. export default (connectionServices);

Here is my index.ts file :

  1. import express from 'express';
  2. import cors from 'cors';
  3. import connectionServices from "./service/connectionService";
  4. function main() {
  5. const app = express();
  6. const service = new connectionServices({
  7. type: "mongodb",
  8. url: "mongodb://localhost:27017",
  9. port: 27017,
  10. database: "users",
  11. synchronize: true,
  12. entities: [
  13. "src/entities/**/*.ts"
  14. ],
  15. });
  16. app.use(cors())
  17. app.get('/users/:id', function (req, res, next) {
  18. res.json({msg: 'This is CORS-enabled for all origins!'})
  19. })
  20. app.listen(80, function () {
  21. console.log('CORS-enabled web server listening on port 80')
  22. })
  23. app.get('/', (req, res) => {
  24. res.send('Well done!');
  25. })
  26. app.listen(4321, () => {
  27. console.log('The application is listening on port 4321!');
  28. })
  29. app.get('/users', (req,res) => {
  30. res.send(service.getUsers());
  31. })
  32. }
  33. main();

And finally here is my ormconfig.json file :

  1. {
  2. "type": "mongodb",
  3. "host": "localhost",
  4. "url": "mongodb://localhost:27017",
  5. "port": 27017,
  6. "database": "test",
  7. "synchronize": true,
  8. "logging": false,
  9. "entities": [
  10. "src/entity/**/*.ts"
  11. ],
  12. "migrations": [ "src/migration/**/*.ts"
  13. ],
  14. "subscribers": [ "src/subscriber/**/*.ts"
  15. ],
  16. "cli": {
  17. "entitiesDir": "src/entity", "migrationsDir": "src/migration", "subscribersDir": "src/subscriber"
  18. }
  19. }

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 文件中。

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

  1. import { createConnection, DataSource, DataSourceOptions } from "typeorm";
  2. import { Utilisateurs } from "../entities/utilisateurs.entity";
  3. class connectionServices {
  4. public myDataSource: DataSource;
  5. async connect() {
  6. await this.myDataSource.connect();
  7. }
  8. constructor(dbConfig: DataSourceOptions) {
  9. this.myDataSource = new DataSource(dbConfig);
  10. }
  11. public async getUsers() {
  12. const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
  13. const data = await myusers.find({});
  14. console.log(data);
  15. return data;
  16. }
  17. }
  18. export default connectionServices;

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

  1. import express from 'express';
  2. import cors from 'cors';
  3. import connectionServices from "./service/connectionService";
  4. import { Utilisateurs } from './entities/utilisateurs.entity';
  5. async function main() {
  6. const app = express();
  7. const service = new connectionServices({
  8. type: "mongodb",
  9. host: "localhost",
  10. port: 27017,
  11. database: "users",
  12. synchronize: true,
  13. entities: [
  14. Utilisateurs
  15. ],
  16. });
  17. await service.connect();
  18. app.use(cors());
  19. app.get('/users/:id', function (req, res, next) {
  20. res.json({ msg: 'This is CORS-enabled for all origins!' });
  21. });
  22. app.listen(80, function () {
  23. console.log('CORS-enabled web server listening on port 80');
  24. });
  25. app.get('/', (req, res) => {
  26. res.send('Well done!');
  27. });
  28. app.listen(4321, () => {
  29. console.log('The application is listening on port 4321!');
  30. });
  31. app.get('/users', async (req, res) => {
  32. res.send(await service.getUsers());
  33. });
  34. }
  35. 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 :

  1. import { createConnection, DataSource, DataSourceOptions } from "typeorm"
  2. import { Utilisateurs } from "../entities/utilisateurs.entity";
  3. class connectionServices{
  4. public myDataSource:DataSource;
  5. async connect(){
  6. await this.myDataSource.connect();
  7. }
  8. constructor(dbConfig: DataSourceOptions){
  9. this.myDataSource = new DataSource(dbConfig);
  10. }
  11. public async getUsers (){
  12. const myusers = this.myDataSource.getMongoRepository(Utilisateurs);
  13. const data = await myusers.find({});
  14. console.log (data);
  15. return data;
  16. }
  17. }
  18. 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 :

  1. import express from 'express';
  2. import cors from 'cors';
  3. import connectionServices from "./service/connectionService";
  4. import { Utilisateurs } from './entities/utilisateurs.entity';
  5. async function main() {
  6. const app = express();
  7. const service = new connectionServices({
  8. type: "mongodb",
  9. host: "localhost",
  10. port: 27017,
  11. database: "users",
  12. synchronize: true,
  13. entities: [
  14. Utilisateurs
  15. ],
  16. });
  17. await service.connect();
  18. app.use(cors())
  19. app.get('/users/:id', function (req, res, next) {
  20. res.json({msg: 'This is CORS-enabled for all origins!'})
  21. })
  22. app.listen(80, function () {
  23. console.log('CORS-enabled web server listening on port 80')
  24. })
  25. app.get('/', (req, res) => {
  26. res.send('Well done!');
  27. })
  28. app.listen(4321, () => {
  29. console.log('The application is listening on port 4321!');
  30. })
  31. app.get('/users', async(req,res) => {
  32. res.send(await service.getUsers());
  33. })
  34. }
  35. 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:

确定