student student - 3 months ago 18
Node.js Question

node js with express not loading mongodb database content

Trying to learn MongoDB for Node.js

I've my

app.js
:



var express = require('express'),
app = express(),
engines = require('consolidate'),
MongoClient = require('mongodb').MongoClient,
assert = require('assert');

app.engine('html', engines.nunjucks);
app.set('view engine', 'html');
app.set('views', __dirname + '/views');

MongoClient.connect('mongodb://localhost:27017/startup', function(err, db) {

assert.equal(null, err);
console.log("Successfully connected to MongoDB.");

app.get('/', function(req, res) {

db.collection('startup').find({}).toArray(function(err, docs) {
res.render('startup', {
'name': docs
});
console.log(docs);

});

});

app.use(function(req, res) {
res.sendStatus(404);
});

var server = app.listen(3000, function() {
var port = server.address().port;
console.log('Express server listening on port %s.', port);
});

});





There're documents in the
startup
collection as well:

documents in the startup collection

And the template file is:



<h1>startups</h1>
{% for s in startup %}
<li><a href="https://www.google.com/search?q={{ s.name }}">{{ s.name }}, {{ s.Founded }}</a>
</li>
{% else %}
<li>No startups found.</li>
{% endfor %}





However, the result says:

no startups found

Can someone point me, where am I wrong?

Answer

You're passing the startups collection as a name property, but in a template you try to access it with startup identifier for some reason.

Change either and you're good.

Comments