很抱歉,我知道有很多问题都在问这个问题,但是我找不到任何答案来解决这个问题!
我尝试使用mongoose填充函数来填充模式的ID,但它只返回一个空数组。如果我不使用populate函数,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的季节字段。
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});
});
};谢谢你的帮助。我无计可施了。
发布于 2021-07-08 15:33:39
大量的面部手掌表情符号。
问题是被引用的季节ID来自不存在的季节。我在填充数据库时不知何故复制了一些内容,并且删除了错误的内容。感觉我浪费了我生命中的两天,但至少它已经解决了!
发布于 2021-07-06 18:09:16
.populate()是一个需要正确调用的异步方法:
exports.fruit_detail = async function(req, res, next) {
await Fruit.findOne({name: req.params.name})
.populate('season')
.execPopulate(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});
});
};然后,您必须导入fruit_deail方法并异步调用它:await this.fruit_detail(req, res, next)
https://stackoverflow.com/questions/68260225
复制相似问题