Connecting and retrieving data from MongoDB doesn't work using nodemon (Mongoose + Typegoose)

346 Views Asked by At

[Contextualizing]

I have a simple NodeJS project using Mongodb, Mongoose (with Typegoose) and Nodemon.

In my package.json I have commands for developer and production environments.

...
"start-dev": "nodemon src/index.ts",
"start-prd": "node dist/index",
...

For the start-prd command, I am using webpack to generate the binaries.

This is my webpack.config.

const webpack = require("webpack");
const path = require("path");
const nodeExternals = require("webpack-node-externals");

module.exports = {
  mode: "dsv",
  entry: ["webpack/hot/poll?100", "./src/index.ts"],
  watch: true,
  target: "node",
  externals: [
    nodeExternals({
      allowlist: ["webpack/hot/poll?100"]
    })
  ],
  module: {
    rules: [
      {
        test: /.tsx?$/,
        use: "ts-loader",
        exclude: /node_modules/
      }
    ]
  },
  resolve: {
    extensions: [".tsx", ".ts", ".js"]
  },
  plugins: [new webpack.HotModuleReplacementPlugin()],
  output: {
    path: path.join(__dirname, "dist"),
    filename: "index.js"
  }
};

I have a Delivery model class mapped with Typegoose ...

import { prop } from '@typegoose/typegoose';
import { Typegoose } from 'typegoose';

export class Delivery extends Typegoose {
    @prop()
    name: string;
    @prop()
    description?: string;
    @prop()
    services: string[];
    @prop()
    rating?: number;
};

... and I define the repository like this.

import mongoose from 'mongoose';
import { Delivery } from '../entities/delivery';

export class DeliveryRepository {

  async list(): Promise<Delivery[]> {
      await mongoose.connect('mongodb://usr:passw@localhost:21017/my_db',
      {
          auth: {
             user:"usr", 
             password:"passw"
          },
          useNewUrlParser: true,
          useUnifiedTopology: true
      });

      const Model = new Delivery().getModelForClass(Delivery, {
          existingMongoose: mongoose,
          schemaOptions: {collection: 'deliveries'}
      });
      return Model.find({});
  }
}

Calling the API with the get method.

...
app.route('/api/deliveries').get((req, res) => {
  var repo = new DeliveryRepository();
  repo.list().then((result) => {
      res.status(200).send(result);
  }).catch(r => console.log(r));
})
...

[Scenario]

If run prd script.

1. npm run webpack
2. npm run start-prd

It works perfectly! I call the api get method and list my objects.

When run dev script.

1. npm run start-dev

Nodemon starts normally, but when calling the api get method error occurs ...

TypeError: Cannot read property '_id' of undefined
    at Schema.add (D:\pessoal\workspaces\omeurestaurante-api\node_modules\mongoose\lib\schema.js:462:11)
    at _buildSchema (D:\pessoal\workspaces\omeurestaurante-api\node_modules\typegoose\src\typegoose.ts:134:9)
    at Delivery.buildSchema (D:\pessoal\workspaces\omeurestaurante-api\node_modules\typegoose\src\typegoose.ts:109:13)
    at Delivery.setModelForClass (D:\pessoal\workspaces\omeurestaurante-api\node_modules\typegoose\src\typegoose.ts:78:22)
    at Delivery.getModelForClass (D:\pessoal\workspaces\omeurestaurante-api\node_modules\typegoose\src\typegoose.ts:52:12)
    at SessionDb.getModel (D:\pessoal\workspaces\omeurestaurante-api\src\db\session-db.ts:29:24)
    at DeliveryRepository.<anonymous> (D:\pessoal\workspaces\omeurestaurante-api\src\repositories\delivery.repository.ts:16:30)
    at Generator.next (<anonymous>)
    at D:\pessoal\workspaces\omeurestaurante-api\src\repositories\delivery.repository.js:8:71
    at new Promise (<anonymous>)
    at __awaiter (D:\pessoal\workspaces\omeurestaurante-api\src\repositories\delivery.repository.js:4:12)
    at DeliveryRepository.list (D:\pessoal\workspaces\omeurestaurante-api\src\repositories\delivery.repository.js:22:16)
    at app.route.get (D:\pessoal\workspaces\omeurestaurante-api\src\index.ts:40:8)
    at Layer.handle [as handle_request] (D:\pessoal\workspaces\omeurestaurante-api\node_modules\express\lib\router\layer.js:95:5)
    at next (D:\pessoal\workspaces\omeurestaurante-api\node_modules\express\lib\router\route.js:137:13)
    at Route.dispatch (D:\pessoal\workspaces\omeurestaurante-api\node_modules\express\lib\router\route.js:112:3)
0

There are 0 best solutions below