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.
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.