【发布时间】:2021-09-16 11:25:55
【问题描述】:
对不起,我知道有很多问题都在问同样的问题,但我找不到任何可以为我解决问题的答案!
我正在尝试使用 mongoose 填充函数来填充模式的 ID,但它只返回一个空数组。如果我不使用填充函数,ID 就在数组中,但使用它似乎会删除它们。
我的路线和模型很简单,因为我只是想学习它,这对于为什么它错了更令人困惑!而且我认为我完全按照教程进行操作......
这些是我的架构:
var SeasonSchema = new Schema(
{
name: {type: String, required: true, enum: ['Spring', 'Summer', 'Autumn', 'Winter']},
description: {type: String, maxLength: 300}
}
);
var FruitSchema = new Schema(
{
name: {type: String, required: [true, 'All fruits have names.'], maxLength: 50},
description: {type: String, maxLength: 300},
season: [{type: Schema.Types.ObjectId, ref: 'Season', required: true}],
price: {type: Number, min: 0, max: 9.99, required: true},
stock: {type: Number, min: 0, max: 999, required: true}
}
);
这是我要开始工作的控制器:(只需填充 Fruit's Season 字段。
exports.fruit_detail = function(req, res, next) {
Fruit.findOne({name: req.params.name})
.populate('season')
.exec(function (err, fruit) {
if (err) {return next(err);}
if (fruit==null) {
var err = new Error('Fruit not found');
err.status = 404;
return next(err);
}
res.render('fruit_detail', {title: fruit.name, fruit: fruit});
});
};
感谢您的帮助。我已经束手无策了。
【问题讨论】:
标签: node.js express mongoose mongoose-schema mongoose-populate