mongodb.js 1.1 KB

123456789101112131415161718192021222324252627282930313233343536
  1. const { MongoClient } = require( "mongodb" );
  2. let World, Fortune;
  3. const dbHost = process.env.DB_HOST || 'localhost'
  4. const projection = { projection: { _id: 0 } }
  5. module.exports = {
  6. async init() {
  7. let client = new MongoClient(`mongodb://${dbHost}:27017`, { minPoolSize: 2, maxPoolSize: 75 })
  8. await client.connect()
  9. let db = await client.db( 'hello_world' );
  10. Fortune = await db.collection( 'fortune' );
  11. World = await db.collection( 'world' );
  12. },
  13. allFortunes: async () => Fortune.find( undefined, projection ).toArray(),
  14. worldById: async ( id ) => World.findOne( { _id: id }, projection ),
  15. allWorlds: async () => World.find( undefined, projection ).toArray(),
  16. bulkUpdateWorld: async worlds =>
  17. World.bulkWrite(
  18. worlds.map( world => ( {
  19. updateOne: {
  20. filter: {
  21. _id: world.id
  22. },
  23. update: {
  24. $set: { randomNumber: world.randomNumber }
  25. }
  26. }
  27. } ) )
  28. ).then(()=>worlds)
  29. }