I use Node.JS, Express, MongoDB and EJS. I have a question about several MongoDB collections under the same database and calling them for use in the interface. I have 3 collections, and after many studies I could not find how to call several collections without errors.
I understand that it would be unimportant to keep everything under one collection, but I believe that the best approach is to separate them into categories. Here is my db / collection call:
app.use(express.bodyParser()); var MongoClient = require('mongodb').MongoClient; app.get('/', function(req, res){ MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) { if(!err) { console.log("We are connected"); } db.collection("portfolio", function(err, collection) { collection.find().sort({order_num: 1}).toArray(function(err, result) { var portfolio = []; if (err) { throw err; } else { for (i=0; i<result.length; i++) { portfolio[i] = result[i]; } res.render('index.html', {portfolio: portfolio}); } }); }); }); });
How can I make some calls for additional collections, such as the "about" collection, etc.? I tried adding more ...
db.collection("about", function(err, collection) {
... in...
MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) {
... but it gives me errors in the terminal console log.
Thanks in advance.
EDIT:
Here is what I am trying to do that gives me an error:
app.get('/', function(req, res){ MongoClient.connect("mongodb://localhost:27017/michael", function(err, db) { if(!err) { console.log("We are connected"); } db.collection("portfolio", function(err, collection) { collection.find().sort({order_num: 1}).toArray(function(err, result) { var portfolio = []; if (err) { throw err; } else { for (i=0; i<result.length; i++) { portfolio[i] = result[i]; } res.render('index.html', {portfolio: portfolio}); } }); });
Here's the error from the console:
ReferenceError: /Volumes/Files/WebDev/RHC/michael/michael/views/index.html:62 60| <div class="row-fluid"> 61| <ul id="work" class="thumbnails"> >> 62| <% for(i=0; i<portfolio.length; i++) { %> 63| <% if (portfolio[i].proj_type == "work") { %> 64| <% var newLine = ""; %> 65| <% var fancyBox = ""; %> portfolio is not defined
So, I have two collections in MongoDB under db called "michael", and I'm trying to call them both under the same MongoClient.connect (). Then I send the results to the front-end (via EJS) in two arrays: "portfolio" and "o". It seems that when I do this, it displays the "portfolio" undefined. Hope this makes sense.