正在为一个新项目开发数据库结构,并试图弄清楚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数组中没有任何内容(引用Image):
images: [{
type: Schema.Types.ObjectId, ref: 'Image'
}]
我认为使用ref可以在Project和Image之间创建外键引用,然后两个Image应该具有链接的Project,而Project应该看到数组中的链接图像。 是不是这样,或者我在这里想念什么?
答案 0 :(得分:1)
您应该可以毫无问题地从项目中填充图像。
假设您有此项目文档:
{
"_id" : ObjectId("5e592a438b93764a40a81a96"),
"images" : [
ObjectId("5e592aba8b93764a40a81a98"),
ObjectId("5e592ac78b93764a40a81a99")
],
"name" : "Project 1",
"__v" : 0
}
这些图像文档:
{
"_id" : ObjectId("5e592ac78b93764a40a81a99"),
"url" : "Url 2",
"project" : ObjectId("5e592a438b93764a40a81a96"),
"__v" : 0
},
{
"_id" : ObjectId("5e592aba8b93764a40a81a98"),
"url" : "Url 1",
"project" : ObjectId("5e592a438b93764a40a81a96"),
"__v" : 0
}
我们可以使用以下代码填充图像:
router.get("/projects/:id", async (req, res) => {
const result = await Project.findById(req.params.id).populate("images");
res.send(result);
});
这将给出如下结果:
{
"images": [
{
"_id": "5e592aba8b93764a40a81a98",
"url": "Url 1",
"project": "5e592a438b93764a40a81a96",
"__v": 0
},
{
"_id": "5e592ac78b93764a40a81a99",
"url": "Url 2",
"project": "5e592a438b93764a40a81a96",
"__v": 0
}
],
"_id": "5e592a438b93764a40a81a96",
"name": "Project 1",
"__v": 0
}
因此,对于您的情况,请检查您的项目文档是否确实包含带有图像文档的对象ID的图像数组,并且您填充正确。
此外,您无需在架构中添加_id字段,mongodb本身会自动生成_id。
项目
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ProjectSchema = Schema({
name: { type: String, required: true, trim: true, maxLength: 60 },
description: { type: String, required: false },
images: [
{
type: Schema.Types.ObjectId,
ref: "Image"
}
]
});
module.exports = mongoose.model("Project", ProjectSchema);
图片
const mongoose = require("mongoose");
const Schema = mongoose.Schema;
const ImageSchema = new Schema({
url: { type: String, unique: true, required: true },
project: {
type: Schema.Types.ObjectId,
ref: "Project"
}
});
module.exports = mongoose.model("Image", ImageSchema);