【发布时间】:2021-07-01 14:14:01
【问题描述】:
我之前在其他 Schema 上创建了 Mongoose virtuals 并没有问题,但我现在有一个不会填充,并且不确定该怎么做。
const InventorySchema = new mongoose.Schema(
{
name: { type: String },
............
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
InventorySchema.virtual('logs', {
ref: 'Log',
localField: '_id',
foreignField: 'inventory',
});
module.exports = mongoose.model('Inventory', InventorySchema);
这是它所引用的日志架构。
const LogSchema = new mongoose.Schema(
{
...other info,
inventory: {
type: mongoose.Schema.Types.ObjectId,
ref: 'Inventory',
},
},
{
toJSON: { virtuals: true },
toObject: { virtuals: true },
}
);
module.exports = mongoose.model('Log', LogSchema);
尽管存在记录,但调用inventory.find 会导致未定义
const inventory = await Inventory.findById(req.params.id).populate('logs');
console.log(inventory.populated('logs')); //undefined
console.log(inventory.logs); //undefined
const invLogs = await Log.find({ inventory: inventory._id });
console.log('invLogs: ', invLogs.length); // 5 - so the records exist
我在这里搜索过,但没有找到适合我的答案。我认为我做错了什么,但我在其他收藏中有类似的虚拟。我应该提一下,我在 Inventory 上使用了 mongoose-autopopulate,我还没有看到它和 virtuals 有任何问题,但我可能是错的。
【问题讨论】:
标签: mongodb mongoose virtual populate