This is how I build a class to connect to my mongoDb before. As you can see, I connect to the Db and also I create a gfs, which uses mongo.GridFSBucket. This is needed to handle image files.
export default class Db {
constructor (uri, callback) {
const mongo = process.env.MONGO || 'mongodb://localhost:27017'
this.mongodb = 'data'
this.db = null
this.gfs = null
this.connection = MongoClient.connect(mongo)
return this
}
async connect (msg) {
if (!this.connected) {
try {
this.connection = await this.connection
this.connection = this.connection.db(this.mongodb)
this.gfs = new mongo.GridFSBucket(this.connection)
this.connected = true
} catch (err) {
console.error('mongo connection error', err)
}
}
return this
}
}
No I switched the backend to a nestJS application and I don't know how to create the gfs instance in a module:
@Module({
providers: [
{
provide: 'DATABASE_CLIENT',
useFactory: () => ({ client: null })
},
{
provide: 'DATABASE_CONNECTION',
inject: ['DATABASE_CLIENT'],
useFactory: async (dbClient): Promise<Db> => {
const mongo = 'mongodb://localhost:27017'
const options = {}
const client = new MongoClient(mongo, options)
try {
await client.connect()
dbClient.client = client
const db = client.db('data')
// How to create a GridFSBucket instance?
// dbClient.gfs = new GridFSBucket(db)
return db
} catch (error) {
console.error(error)
}
}
}
],
exports: ['DATABASE_CONNECTION', 'DATABASE_CLIENT']
})
export class DatabaseModule {
constructor(@Inject('DATABASE_CLIENT') private dbClient) {}
onApplicationShutdown(signal) {
if (signal) console.log(signal + ' signal recieved') // e.g. "SIGINT"
}
}
Also this gfs should be returned only if needed. The DatabaseModule is used like this in any other module, which needs db connection:
@Module({
imports: [DatabaseModule],
providers: [PhotosService, PhotosResolvers]
})
export class PhotosModule {}
But not every module needs the gfs instance, so I need to pass something like useGfs = true. How do I pass a parameter?