Search code examples
node.jsexpressmongooseejsembedded-javascript

Express making mongodb data available in route


This seems like a relatively simple issue, but I can't seem to find good documentation. I'd like to pass json data from mongodb into a route, so that it is available in my ejs template.

My schema is:

var GiveSchema   = new Schema({
    title: String,
    shortname: String,
    contents: String,
    image: String,
    category: String
});

module.exports = mongoose.model('GiveData',  GiveSchema);

var Givedata = mongoose.model( 'GiveData' );

I'd like to pass make it available to my route below, as the variable list:

app.get('/', function(req, res) {
    res.render('index.ejs',{
      list: Givedata,
      bootstrappedUser: req.user,
      page: 'home'
    });
});

Solution

  • You'll still need to query the database for your items.

    app.get('/', function(req, res, next) {       
       Givedata.find(function(err, items){
         if(err) { return next(err); }
         res.render('index.ejs',{
           list: items,
           bootstrappedUser: req.user,
           page: 'home'
         });
      });
    });