【问题标题】:Problems with Mongoose populateMongoose 的问题
【发布时间】:2018-12-30 01:10:13
【问题描述】:

游戏架构

const { Schema, model } = require('mongoose');

const gameSchema = Schema({
  _id: Schema.Types.ObjectId,
  name: { type: String, required: true },
  description: String,
  calc: [{ type: Schema.Types.ObjectId, ref: 'Calc' }]
});

module.exports = model('Game', gameSchema);

计算架构

const { Schema, model } = require('mongoose');

const calcSchema = Schema({
  _id: Schema.Types.ObjectId,
  preset: { type: String, required: true },
  datasets: [{ type: Schema.Types.ObjectId, ref: 'Dataset' }],
  model: String,
});

module.exports = model('Calc', calcSchema, 'calc');

获取游戏路线

router.get('/', passport.authenticate('jwt', { session: false }), (req, res) => {
  Game.find()
    .select('_id name calc')
    .populate('calc')
    .then(games => res.status(200).json(games))
    .catch(err => res.status(500).json({ error: err }));
});

不是用 Calc 对象填充 calc 属性,而是替换 ids,calc 属性变成一个空数组。如何正确使用填充?我的代码中是否有明显的错误?

简而言之:populate() 的结果是 calc: [] 而不是 calc: [{Calc object}, ...]

【问题讨论】:

  • 您到底想达到什么目的?目前还不清楚您的问题和您面临的问题。请编辑您的问题。

标签: node.js mongodb express mongoose


【解决方案1】:

在您的情况下,您正在尝试填充一组文档(而不仅仅是一个文档),因此您应该改用 Model.populate() 方法。

Game.find()
  .select('_id name calc')
  .then(games => Game.populate(games, { path: 'calc' }))
  .then(games => res.status(200).json(games))
  .catch(err => res.status(500).json({ error: err }));

【讨论】:

  • 不幸的是,.then(games => Game.populate({ path: 'calc' })) 触发了 catch 块。err 是一个空对象。
  • 对不起,我忘记了第一个参数。这是 Game.populate(games, { path: 'calc' })
猜你喜欢
  • 2015-10-26
  • 2011-10-09
  • 2019-12-04
  • 1970-01-01
  • 1970-01-01
  • 2019-12-03
  • 2018-01-13
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多