【发布时间】:2020-06-12 15:44:31
【问题描述】:
为一个新项目处理数据库结构,并试图弄清楚 MongoDB / mongoose 中的一对多关系究竟是如何工作的。
所以考虑以下简单的结构:
我有一个项目表/模式,其中链接了多个图像:
const ProjectSchema = mongoose.Schema({
_id: mongoose.Types.ObjectId, // Just the id,
name: { type: String, required: true, trim: true, maxLength: 60 },
description: { type: String, required: false },
images: [{
type: Schema.Types.ObjectId, ref: 'Image'
}]
});
然后是图像表/模式:
const ImageSchema = new Schema({
_id: mongoose.Types.ObjectId, // Just the id,
url: { type: String, unique: true, required: true }
project: {
type: Schema.Types.ObjectId, ref: 'Project'
}
});
我想要图像和项目之间的一对多,所以我用项目 id 保存了一个图像:
const image = new Image(
{
project: project._id,
_id: new mongoose.Types.ObjectId(),
url: 'https://someurl',
});
await image.save();
如果我随后找到此图像并填充项目字段 - 它很好地包含所有项目信息,但如果我找到此项目,则图像数组中没有任何内容(引用图像):
images: [{
type: Schema.Types.ObjectId, ref: 'Image'
}]
我认为使用 ref 您正在创建 Project 和 Image 之间的外键引用,然后 Image 应该具有链接的 Project 并且 Project 应该在数组中看到链接的图像。 不是这样还是我在这里遗漏了什么?
【问题讨论】:
-
如何查询项目?