我正在学习平均堆栈,并希望在使用express进行路由时选择多个模型。我需要选择一个模型,然后根据它的值,其他几个。以下是主要的模型:
var mongoose = require('mongoose');
var MatchSchema = new mongoose.Schema({
title: String,
type: [{ type: mongoose.Schema.Types.ObjectId, ref: 'Game' }],
owner: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }],
players: [{ type: mongoose.Schema.Types.ObjectId, ref: 'User' }]
});
mongoose.model('Match', MatchSchema);根据类型所有者和玩家,我需要选择游戏和用户模型,但我被困在这样做。这是我目前的路线,它只选择匹配模型。
router.get('/games', function (req, res, next) {
Match.find(function (err, matches) {
if (err) {
console.log(err);
return next(err);
}
res.json(matches);
});
});所以我需要循环所有的比赛,对于每一个选择属于它的类型的游戏模型和属于所有者和玩家的用户模型,我将如何去做呢?
发布于 2015-05-11 08:56:38
如果我理解你的问题正确,那么你必须填充你的子文档。
猫鼬有能力为你做这些。基本上,你必须这样做:
router.get('/games', function (req, res, next) {
Match
.find({})
.populate('type').populate('owner').populate('players')
.exec(function (err, matches) {
if (err) return handleError(err);
res.json(matches);
});
});有关更多信息,请参阅猫鼬文档:http://mongoosejs.com/docs/populate.html
发布于 2015-05-11 08:08:10
您可以使用嵌套代码,如
Match.find(function (err, matches) {
if (err) {
console.log(err);
return next(err);
}
Game.find(function (err, games) {
if (err) {
console.log(err);
return next(err);
}
Users.find(function (err, user) {
if (err) {
console.log(err);
return next(err);
}
res.json({matches:matches, games:games, user:user});
});
});
});https://stackoverflow.com/questions/30162405
复制相似问题