mongo.js 1.0 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950
  1. const MongoClient = require("mongodb").MongoClient;
  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 MongoClient.connect(
  8. mongoUrl,
  9. { useNewUrlParser: true }
  10. );
  11. }
  12. const db = client.db(dbName);
  13. return db.collection(name);
  14. }
  15. async function allFortunes() {
  16. const collection = await getCollection("fortune");
  17. const fortunes = await collection.find({}, { projection: { _id: 0 } });
  18. return fortunes.toArray();
  19. }
  20. async function getWorld(id) {
  21. const collection = await getCollection("world");
  22. return collection.findOne({ id }, { projection: { _id: 0 } });
  23. }
  24. async function saveWorlds(worlds) {
  25. const collection = await getCollection("world");
  26. const bulk = collection.initializeUnorderedBulkOp();
  27. worlds.forEach(world => {
  28. bulk.find({ id: world.id }).updateOne(world);
  29. });
  30. return bulk.execute();
  31. }
  32. module.exports = {
  33. getWorld,
  34. saveWorlds,
  35. allFortunes
  36. };