mongo.js 979 B

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