Import var into matches.ejs

Hello guys im a bit stuck in project. I’m trying to import my var results into matches.ejs

Here is a function I received some help to create

matches.js

module.exports = {
  getCustomers: function(callback) {
    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://127.0.0.1:27017/test";

    MongoClient.connect(url, function(err, db) {
      if (err) throw err;
      var dbo = db.db("mydb");
      dbo.collection("customers").find({}).toArray(function(err, result) {
        if (err) throw err;
        db.close();
        callback(result);
      });
    });
    }
    };

And testing it in console.log works

var db = require('./app/settings');
db.getCustomers(function(results) {
  console.log("customers", results);
 });

However in my routes.js file I would Like this var to be imported when it renders matches.ejs

I have tried like so:

app.get('/profile', isLoggedIn, function(req, res) {
	res.render('pages/matches.ejs', {
	  result: db.getCustomers(results)
	});
});

But does not work any suggestion as how I can pass the var over to matches.ejs would be much appreciated’’

Hi @frederikwalle,

Judging by this and your other, similar thread, I’m guessing you’re not fully familiar with synchronous vs asynchronous code.

In your route, you’re treating db.getCustomers() as a synchronous operation - i.e. you’re expecting it to return a result before the rest of the code executes. However, the MongoDB client methods are asynchronous - when you call them, JS doesn’t wait for them to finish before moving on, which is why you have to provide a callback function (there are also other ways of dealing with async code).

You’ve got this right in your console.log() test - you just need to apply this to your route function.

thanks for your reply and insight into my misconception with synchronous vs asynchronous code. I did find this excelent articel here: https://www.pluralsight.com/guides/front-end-javascript/introduction-to-asynchronous-javascript

which have given me a bettor grasp of things but still I have a lot to learn.

“You’ve got this right in your console.log() test - you just need to apply this to your route function.”

  • I know I have it right here but i’m actually clueless as how to add/rewrite this to work my routes routine, hence my cry for help here. I was hoping for a sample if you don’t mind .

  • I have tried a few different approaches but with my skill level i really need some help :slight_smile:

Frederik

app.get('/profile', isLoggedIn, function(req, res) {
  db.getCustomers(function(results) {
    res.render('pages/matches.ejs', {
      result: results;
    })
  });
});

Note that you’ll need to add some error checking, but that’s the general idea.

phew this was very close to some of earlier tests today. Much appreciated sir

Ill look forward to test this…

frederik

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.