2014-03-02 63 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}) 
    }); 


});