2014-03-02 64 views
0

我很容易地和成功地通过一个单一的模式到一个视图中我明确的途径之一是这样的:如何将多个模型传递到视图中?

exports.locations = function(req, res){ 
    Location.find(function(err, results) { 
     res.render('locations', { title: 'Locations', locations: results }); 
    }); 
}; 

我有,我需要通过2个结果集到另外一个途径,我该怎么办那?我曾尝试这样做,但它似乎并不奏效:

exports.locationdetail = function(req, res) { 
    var packages = Package.find(); 
    Location.findById(req.params.id, function(err, result) { 
     res.render('location-detail', { title: 'Location Details', location: result, packages: packages }); 
    }); 
}; 

编辑1

我得到的错误是:

Cannot read property 'name' of undefined 

我的模型看起来像这样:

var mongoose = require('mongoose') 
    ,Schema = mongoose.Schema; 

var PackageSchema = new mongoose.Schema({ 
    name: String, 
    prev_package: String, 
    featured: Boolean, 
    services: Array 
}); 

module.exports = mongoose.model('Package', PackageSchema); 

我在另一个视图中使用这个模型,克就像冠军一样工作。

+0

@hexacyanide我刚刚更新了我一些你正在寻找的信息的问题。这有帮助吗? – drewwyatt

回答

0

因此,它看起来像是另一个异步“陷阱”。把这个变成一个嵌套回调的伎俩:

exports.locationdetail = function(req, res) { 
    Location.findById(req.params.id, function(err, result) { 
     Package.find(function (err, results) { 
      res.render('location-detail', { title: 'Location Details', location: result, packages: results }); 
     }); 
    }); 
}; 
0
var mongoOp  = require("./models/mongo"); 
var async = require('async'); 

router.get("/",function(req,res){ 
    var locals = {}; 
    var userId = req.params.userId; 
    async.parallel([ 
     //Load user data using Mangoose Model 
     function(callback) { 
      mongoOp.User.find({},function(err,user){ 
       if (err) return callback(err); 
       locals.user = user; 
       callback(); 
      }); 
     }, 
     //Load posts data using Mangoose Model 
     function(callback) { 
       mongoOp.Post.find({},function(err,posts){ 
       if (err) return callback(err); 
       locals.posts = posts; 
       callback(); 
      }); 
     } 
    ], function(err) { //This function gets called after the two tasks have called their "task callbacks" 
     if (err) return next(err); //If an error occurred, we let express handle it by calling the `next` function 
     //Here `locals` will be an object with `user` and `posts` keys 
     //Example: `locals = {user: ..., posts: [...]}` 


     res.render('index.ejs', {quotes: locals.user,userdata: locals.posts}) 
    }); 


});