node.jsmoleculer

`this.adapter` is `undefined`. when execute the action in moleculer action


I have created a moleculer project as below: https://codesandbox.io/s/8d5xy3
now I changed default database to mongodb/mongoose:

but when I run products.service.js's action: createProduct, I get 500 error:

{
  "name": "MoleculerError",
  "message": "Could not create product",
  "code": 500,
  "type": "CREATE_PRODUCT_ERR",
  "data": {
    "error": "Cannot read properties of undefined (reading 'insert')"
  }
}

action code:

        createProduct: {
            rest: {
                method: "PUT",
                path: "/product"
            },
      params: {
        name: "string",
        price: "number",
                quantity: "number",
      },
      async handler(ctx) {
        const { name, price, quantity } = ctx.params;

        try {
                    console.log({name, price, quantity}, this.adapter)
          const product = await this.adapter.insert({ name, price, quantity });
                    
          return product;
        } catch (err) {
          throw new MoleculerError("Could not create product", 500, "CREATE_PRODUCT_ERR", { error: err.message });
        }
      }
    },

After debugging, I find the reason: this.adapter is undefined.

I don't know how to solve this problem, please help.


Solution

  • First, you must figure out why you don't use the package [from the readme instructions] (https://github.com/moleculerjs/moleculer-db/tree/master/packages/moleculer-db-adapter-mongoose#usage) you won't have any problems with it, the code is written there correctly.

    In your code 2 different mixins are working with the database performing incomprehensible actions.

    In the plugin mongo.db.mixin.js you added adapter to schema service, but you skipped connecting moleculer-db which creates this this.adapter so it is undefined, in your current code it is accessible by this.schema.adapter which is wrong.

    Unfortunately, you haven't figured out how mixin and schema interact in moleculer, so it will be hard for you to write your own implementation without that knowledge. Start by studying the source code of the [moleculer-db package] (https://github.com/moleculerjs/moleculer-db/blob/master/packages/moleculer-db/src/index.js#L1074) you want to use and you will understand how everything works better.