Guest User

Untitled

a guest
Nov 16th, 2018
87
0
Never
Not a member of Pastebin yet? Sign Up, it unlocks many cool features!
text 1.54 KB | None | 0 0
  1. // Import express
  2. var express = require('express');
  3. var app = express();
  4.  
  5. // Get MongoClient
  6. var MongoClient = require('mongodb').MongoClient;
  7.  
  8. // db url, collection name and db name
  9. const dburl = 'mongodb://localhost:27017';
  10. const dbname = 'tododb';
  11. const collname = 'todolist';
  12.  
  13. // process root url '/'
  14. app.get('/', function(req, res) {
  15.  
  16. // connect to DB
  17. MongoClient.connect(dburl, function(err, client) {
  18. if (!err) {
  19.  
  20. // Get db
  21. const db = client.db(dbname);
  22.  
  23. // Get collection
  24. const collection = db.collection(collname);
  25.  
  26. // Find all documents in the collection
  27. collection.find({}).toArray(function(err, todos) {
  28. if (!err) {
  29.  
  30. // write HTML output
  31. var output = '<html><header><title>Todo List from DB</title></header><body>';
  32. output += '<h1>TODO List retrieved from DB</h1>';
  33. output += '<table border="1"><tr><td><b>' + 'Description' + '</b></td><td><b>' + 'Details' + '</b></td></tr>';
  34.  
  35. // process todo list
  36. todos.forEach(function(todo){
  37. output += '<tr><td>' + todo.description + '</td><td>' + todo.details + '</td></tr>';
  38. });
  39.  
  40. // write HTML output (ending)
  41. output += '</table></body></html>'
  42.  
  43. // send output back
  44. res.send(output);
  45.  
  46. // log data to the console as well
  47. console.log(todos);
  48. }
  49. });
  50.  
  51. // close db client
  52. client.close();
  53. }
  54. });
  55. });
  56.  
  57. // listen on port 3000
  58. app.listen(3000, function() {
  59. console.log('Example app listening on port 3000!')
  60. });
Add Comment
Please, Sign In to add comment