I am using Mongoose to deal with images. Should I allow one document for every single image or place multiple images into a single document using arrays. I mean, which of these schemas is better —
new mongoose.Schema({
image: [{
title: String,
description: String,
url: String,
}],
});
or this —
new mongoose.Schema({
title: String,
description: String,
url: String,
});
With first approach, we would be having only one document.
Edit: To provide a big picture — we have been using 3 collections (in addition to other collections meant for other things) — landingPageGallery
, subPageGallery
and subPageGalleryArchived
. Each of these three collections store only one document and these documents have a single array storing URLs and other details of about images for landing page and subpages. subPageGalleryArchived
stores images which were previously in subPageGallery
but are now archived. These collections are used to render webpage. We have less than a dozen pages and each page is expected to have around a dozen image.
Edit: I understood the use case incorrectly. Generally as for most questions, the answer is "it depends". You can refer to the following guide for comparison.
How to design data schemas for MongoDB database depends largely on how you access it.
If you have an entity like a web page that always contains certain set of images. And you always need to load them together, the first approach is preferable, as you can query the database only once to get all the data you need.
If your images relate to many other documents, you will want to query the images based on the relationship or some condition, then the second option is more suitable.
If you don't want to associate the images with any other entities, the first option is feasible for small amount of images, otherwise, based on the fields you provide, I assume the first option is to have one document to store images indefinitely. This is not a good idea.
MongoDB has a 16MB document size limit so one day you will might hit the limit if you store a lot of images.
Also many operations a document level. For a real use case you might want to apply filter, sort, group, update, delete operations on images. It's much easier to do that when they're stored as documents.