0

I am working on to do list app using mongoDB and node.js. Basically you type what you want to do then click add. I successfully connected the database but it doesn't show the text that's in the database. It shows only the bullets in the localhost.

Here's the code:

app.get('/', function(req, res) {
  db.collection('list').find().toArray(function (err, result) {
    console.log(result);
    if (err) {return};
    console.log(err);
res.render('index.ejs', {list: result})
 });
});

app.post('/', function(req, res){
 console.log(req.body);
  db.collection('list').save(req.body, function(err, result) {
  if (err) {return};
  console.log(err);

  console.log('saved')
  res.redirect('/');
 })
})
Grace
  • 1
  • 4

1 Answers1

1

I have validated the code you posted and have revised it slightly with comments. I hope this helps but it seems that the fault might be in the res.render method that is being used. Please refer to the following code:

// Requires
var express = require('express');
var bodyParser = require('body-parser');
var MongoClient = require('mongodb').MongoClient;
// Instantiation
var app = express();
var mongopath = "mongodb://localhost:27017/BitX";
// Port number the REST api works on
var portnum = 7500;
// MongoDB object
var db = null;
MongoClient.connect(mongopath, function(err,ldb){
  db = ldb;
});

// Implement Body Parser
app.use(bodyParser.urlencoded({
    extended: false
}));
app.use(bodyParser.json());

// Start the REST service
var server = app.listen(portnum, function() {
    var host = server.address().address;
    var port = server.address().port;
    console.log("Content Provider Service listening at http://%s:%s", host, port);
});

// Default route
app.get('/', function(req, res) {
  // Find all items in orders and send back results to a front end
  db.collection('orders').find().toArray(function (err, result) {
    res.send(result);
    // Consider that the rendering engine may not be functioning correctly
    // SEE MORE: https://stackoverflow.com/questions/21843840/what-does-res-render-do-and-what-does-the-html-file-look-like
    //res.render('index.ejs', {list: result})
 });
});

// Accept a post on the root
app.post('/', function(req, res){
  //Save into orders
  db.collection('orders').save(req.body, function(err, result) {
    res.send(true);
    //res.redirect('/');
  });
});

For additional information on the res.render method please have a look at: What does "res.render" do, and what does the html file look like? - if you have not already.

Hope it helps!

Greg Rebisz
  • 156
  • 7