skip to Main Content

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 :
enter image description here

However when I type in the url http://localhost:4321/users, I get this error in my terminal and the backend crashes :
enter image description here

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!

2

Answers


  1. Chosen as BEST ANSWER

    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.


  2. 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.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search