游戏架构
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 对象填充 calc 属性,而是替换 id,而是变成一个空数组。如何正确使用填充?我的代码中是否有明显的错误?
简而言之:populate() 结果是 calc: [] 而不是 calc: [{Calc 对象}, ...]
在您的情况下,您正在尝试填充一个文档数组(而不仅仅是一个文档),因此您应该改用 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 }));