快速选择多个模型数据

Express selecting multiple model data

我正在学习 MEAN 堆栈并希望在使用 express 进行路由时 select 多个模型。我需要 select 一个模型,然后根据它的值再创建一些其他模型。 这是主要模型:

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

根据类型所有者和玩家,我需要 select 游戏和用户模型,但我坚持这样做。这是我当前的路线,仅 select 是 Matches 模型。

router.get('/games', function (req, res, next) {
  Match.find(function (err, matches) {
    if (err) {
      console.log(err);
      return next(err);
    }

    res.json(matches);
  });
});

所以我需要遍历所有匹配项,对于每个 select 属于它类型的游戏模型以及属于所有者和玩家的用户模型,我将如何着手去做那?

您可以使用嵌套代码,例如

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

如果我理解你的问题是正确的,那么你必须填写你的子文档。

猫鼬有能力为您做到这一点。基本上你必须做这样的事情:

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