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

自闭症网瘾萝莉.ら 提交于 2019-12-23 05:40:43

问题


I'm building an app with Meteorjs. I have a collection that is initialized as:

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

in which I also want to store the images of the corresponding place. I've added the collectionFS package to my project. The following code creates a separate collection for the images:

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

However, I fail to understand how am I supposed to associate this set of images to its relevant document in 'Places'. Or simply insert an image in my mongo collection.


回答1:


This is a common case in Meteor/Mongo where you want to relate two collections. The mongo docs have a good writeup on this.

Let's say each place can have many images. You can either put a reference to the place inside the image or refer to the many images from the place.

When you create an image in collectionFS (leaving out the specifics), make sure to keep the _id of the image:

imgId = image.insert();

If you want to have the image refer to the place you can then update the image with:

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

or you can $push imgId onto an array of images inside your place:

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

The second form of reference is a bit more flexible in that the same image can belong to multiple places (many-to-many). This is good for nested places, for example a picture of Times Square is both a picture of Times Square and a picture of New York City and so on.

Either way you can join your image and Places collections using the reywood:publish-composite package which is designed for easy publishing of related collections.

Note also that a common convention for naming collections in Meteor is first letter capitalized and plural form. i.e. Images instead of image. This is because collections are global variables in Meteor and a collection holds many of the thing that it's named after.



来源:https://stackoverflow.com/questions/33724787/meteorjs-linking-images-fs-collection-to-their-relevant-document-in-the-mong

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!