mongo.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253
  1. const { MongoClient } = require("mongodb");
  2. const mongoUrl = "mongodb://tfb-database:27017";
  3. const dbName = "hello_world";
  4. let client;
  5. async function getCollection(name) {
  6. if (!client) {
  7. client = await new MongoClient(
  8. mongoUrl,
  9. {
  10. useNewUrlParser: true,
  11. useUnifiedTopology: true
  12. }
  13. ).connect();
  14. }
  15. const db = client.db(dbName);
  16. return db.collection(name);
  17. }
  18. async function allFortunes() {
  19. const collection = await getCollection("fortune");
  20. const fortunes = await collection.find({}, { projection: { _id: 0 } });
  21. return fortunes.toArray();
  22. }
  23. async function getWorld(id) {
  24. const collection = await getCollection("world");
  25. return collection.findOne({ id }, { projection: { _id: 0 } });
  26. }
  27. async function saveWorlds(worlds) {
  28. const collection = await getCollection("world");
  29. const bulk = collection.initializeUnorderedBulkOp();
  30. worlds.forEach(world => {
  31. bulk.find({ id: world.id }).updateOne(world);
  32. });
  33. return bulk.execute();
  34. }
  35. module.exports = {
  36. getWorld,
  37. saveWorlds,
  38. allFortunes
  39. };