Connect to https://cloud.mongodb.com/ → Then Database → create a cluster → Shared (free) → (in Database Access) create a user + password → download MongoDB Compass app (or use any other methods to connect).
Connect with
mongodb+srv://<user>:<password>@cluster0.1amio.mongodb.net/test
Create a new database, let say “nestjs” and a new collection “test”
☝️ Back to top!
// mongodb-db.provider.ts
import { Db, MongoClient } from 'mongodb';
export const MongoFactory = async (): Promise<Db> => {
const uri = `mongodb+srv://${process.env.MONGO_USER}:${process.env.MONGO_PASSWORD}@${process.env.MONGO_HOST}`;
try {
const client = await MongoClient.connect(uri, {
useUnifiedTopology: true
});
return client.db(`${process.env.MONGO_DATABASE}`);
} catch (e) {
throw e;
}
};
export const mongodbDatabaseFactory = {
provide: 'MONGO_DB',
useFactory: MongoFactory
};
// In a shared module
import { mongodbDatabaseFactory } from './providers/mongodb-db.provider';
@Global()
@Module({
providers,
exports: [mongodbDatabaseFactory],
controllers: [SecurityController]
})
export class CoreModule {}
Then use it in any service,
// app.service.ts
import { Db } from 'mongodb';
@Injectable()
export class AppService {
constructor(@Inject('MONGO_DB') private db: Db) {
async sampleMethod(): Promise<any> {
return this.db.collection('collectionName').aggregate(pipeline).toArray()
}
}
☝️ Back to top!