0

I keep getting this error whenever I send the request to a different endpoint second time alrhough it is returning the value before crashing the app.

Below is the code of the both requests:

    import { Router } from 'express';
    import WordsStore from '../models/WordsStore';
    
    const wordsRouter = Router();
    const Words = new WordsStore();
    
    wordsRouter.get('/', (req, res) => {
      Words.getAllWords((words) => {
        res.status(200).json(words);
      });
    });
    
    wordsRouter.get('/:id', (req, res) => {
      Words.getOneWord(req.params.id, (word) => {
        if (word) {
          return res.status(200).json(word);
        } else if (word === null) {
          return res.status(404).send(`Word not found`);
        }
      });
    });
    
    export default wordsRouter;

It crashes when I send get requeat to the .../:id endpoint and then to .../ endpoint.

Below is Words class code:

import { connectDB } from '../utils/MongoUtil';
import mongoose from 'mongoose';
const { Schema } = mongoose;

export interface Word {
  id: string;
  group: number;
  page: number;
  word: string;
  author: string;
  image: string;
  audio: string;
  audioMeaning: string;
  audioExample: string;
  textMeaning: string;
  textExample: string;
  transcription: string;
  wordTranslate: string;
  textMeaningTranslate: string;
  textExampleTranslate: string;
}

const WordSchema = new Schema({
  id: {
    type: String,
    unique: true,
  },
  group: Number,
  page: Number,
  word: String,
  image: String,
  audio: String,
  audioMeaning: String,
  audioExample: String,
  textMeaning: String,
  textExample: String,
  transcription: String,
  wordTranslate: String,
  textMeaningTranslate: String,
  textExampleTranslate: String,
});

export const WordsModel = mongoose.model('Words', WordSchema);

export default class WordsStore {
  getAllWords(success: (data: mongoose.Document[]) => void): void {
    connectDB(() => {
      WordsModel.find({}).then((data) => {
        success(data);
        mongoose.connection.close();
      });
    });
  }

  getOneWord(requestedId: string, success: (data: mongoose.Document) => void): void {
    connectDB(() => {
      WordsModel.findOne({ _id: requestedId }).then((data) => {
        success(data);
        mongoose.connection.close();
      });
    });
  }
}

What is my issue?

0 Answers0