How to set MongoDB with moleculer framework

362 views Asked by At

I am new in moleculer framework. I want to store the data in mongoDB which received from moleculer framework.

In sort i want to MongoDB instead of moleculer-db it is possible ?

Please help me. Thanks.

2

There are 2 answers

0
1XTR On

I use mongoose with mixins. Here is gist with example.

import mongoose from 'mongoose'
import { mainSchema } from '../schemas.js'

/**
 * @type {import('moleculer').ServiceSchema}
 */
// eslint-disable-next-line import/prefer-default-export
export const mongoDbMixin = {
  name: 'mongoDbMixin',
  async started() {
    const dbName = this.getEnv('MONGODB_DATABASE')
    const mongoUri = this.getEnv('MONGO_HOSTS')
    try {
      this.DB = await mongoose
        .createConnection(`mongodb://${mongoUri}`, {
          authSource: dbName,
          dbName,
          user: this.getEnv('MONGODB_USER'),
          pass: this.getEnv('MONGODB_PASSWORD'),
          ssl: false,
          tls: false,
          retryWrites: true,
          connectTimeoutMS: 5000,
          autoIndex: this.getEnv('NODE_ENV') === 'development',
          family: 4,
          replicaSet: mongoUri.includes('rs01') ? 'rs01' : undefined,
          writeConcern: {
            w: 'majority',
          },
        })
        .asPromise()
    } catch (error) {
      this.logger.error('initMongoDB error', { error })
      throw new Error('init Mongo connection failed')
    }

    this.logger.info(`MongoDB state = ${mongoose.STATES[this.DB.readyState]}`)

    /**
     * @type {I_MAIN_MODEL}
     */
    this.DB_Main = this.DB.model('Main', mainSchema)

  },
}

/*
main.service.js

import { mongoDbMixin } from '../mixins/mongodb.mixin.js'

const mainServiceSchema = {
  name: 'main',
  mixins: [ mongoDbMixin ],
  actions: {
    find() {
      return this.DB_Main.find({})
    },
  },
}

export default mainServiceSchema

*/
0
André Mazayev On

If you don't want to use moleculer-db then you need to write the connection logic and the actions yourself. In order to establish the connection with the DB you need to use lifecycle events. Take a look at this example. Instead of DB connection it creates an HTTP server but the logic is the same. After that, just write your actions