Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Store variable data after query with mongoose and node.js

Store variable data after query with mongoose and node.js

Problem

I have code in app.js

    var Song = db.model('Song');
    var Album = db.model('Album');

I want to render to index.jade with 2 variables are list of song and list of album
I use query like this

Song.find({}, function( err, docs ){
// .........
}
Album.find({}, function( err, docs ){
// .........
}

So, what should i do to store list of song and list of album to variables and render to index.jade with 2 lists

Problem courtesy of: Huy Tran

Solution

I think you mean something like this:

function( req, res ) { // whatever your "controller" function is
  Song.find({}, function( err, songs ){
    Album.find({}, function( err, albums ){
      res.render('index', { song_list: songs, album_list: albums });
    });
  }); 
}

Then just iterate and markup your song_list and album_list arrays in the template.

Note that this is synchronous and therefore slower than an async approach, but it should do what you want. To go the async route, consider using a library like this to defer res.render until both queries are done: https://github.com/kriszyp/promised-io

Solution courtesy of: glortho

Discussion

View additional discussion.



This post first appeared on Node.js Recipes, please read the originial post: here

Share the post

Store variable data after query with mongoose and node.js

×

Subscribe to Node.js Recipes

Get updates delivered right to your inbox!

Thank you for your subscription

×