我很容易并成功地将单个模型传递到我的一条快速路线中的视图中:
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 :(得分:1)
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})
});
});
答案 1 :(得分: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 });
});
});
};