使用mongoose和node.js存储查询后的变量数据

Store variable data after query with mongoose and node.js

本文关键字:变量 数据 查询 存储 mongoose node js 使用      更新时间:2023-09-26

我在app.js 中有代码

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

我想用两个变量list of songlist of album渲染到index.jade
我使用类似的查询

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

那么,我应该如何将list of songlist of album存储到variables,并使用2个列表渲染到index.jade

我想你的意思是这样的:

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 });
    });
  }); 
}

然后在模板中迭代并标记song_listalbum_list数组。

请注意,这是同步的,因此比异步方法慢,但它应该做您想做的事情。要执行异步路由,请考虑使用这样的库来推迟res.render,直到两个查询都完成:https://github.com/kriszyp/promised-io