Skip to content

Instantly share code, notes, and snippets.

@1xtr
Created October 30, 2023 08:51
Show Gist options
  • Save 1xtr/0f09e74877558e6949c99965745b00bd to your computer and use it in GitHub Desktop.
Save 1xtr/0f09e74877558e6949c99965745b00bd to your computer and use it in GitHub Desktop.
moleculer mongodb mixin
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
*/
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment