MeteorJS - 将图像 (FS.collection) 链接到 MongoDB Collection 中的相关文档

MeteorJS - Linking images (FS.collection) to their relevant document in the MongoDB Collection

我正在使用 Meteorjs 构建应用程序。我有一个 collection 初始化为:

Places=new Mongo.Collection('places');

其中我也想存放相应地方的图片。我已将 collectionFS 包添加到我的项目中。以下代码为图像创建一个单独的 collection:

image=new FS.Collection("images", {
    stores: [new FS.Store.FileSystem("images")]
});

但是,我不明白我应该如何将这组图像与 'Places' 中的相关文档相关联。或者直接在我的 mongo collection.

中插入一张图片

这是 Meteor/Mongo 中的常见情况,您想要关联两个 collection。 mongo docs 对此有一篇很好的文章。

假设每个地方可以有很多图像。您可以在图片中引用该地点,也可以引用该地点的许多图片。

当您在 collectionFS 中创建图像时(省略细节),请确保保留图像的 _id

imgId = image.insert();

如果你想让图像引用你可以更新图像的地方:

image.update({ _id: imgId },{ $set: { placeId: myPlace._id }});

或者您可以 $push imgId 到您所在位置的一系列图像上:

Places.update({ _id: myPlace._id },{ $push: { imageArray: imgId }});

第二种引用形式更灵活一些,因为同一张图片可以属于多个地方(many-to-many)。这对于嵌套位置很有用,例如 时代广场 的图片既是 时代广场 的图片又是 的图片纽约市

无论哪种方式,您都可以使用专为轻松发布相关 collections.

另请注意,在 Meteor 中命名 collections 的常见约定是 首字母大写 复数形式。即 Images 而不是 image。这是因为 collections 是 Meteor 中的全局变量,并且 collection 包含许多以它命名的东西。