Huy Tran
Huy Tran

Reputation: 4441

Store variable data after query with mongoose and node.js

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

Upvotes: 0

Views: 971

Answers (1)

glortho
glortho

Reputation: 13198

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

Upvotes: 1

Related Questions