Search code examples
node.jsmongodbexpressmongoosemongoose-schema

Mongoose crud on nested documents


I am a beginner at mongodb and I would like to receive your advice concerning the best practices to adopt.

I'm working on create a simple blog to start and my mongoose schemas are like this

blog

const Blog = new Schema({
    title : String,
    description : String,
    pictures: Schema.Types.Mixed
});

picture

const picture = new Schema({
    images : Array
});

the image schema will only contain the urls, images will be stored on cloudinary.

I separated into two schemas so as not to duplicate the logic because I could also add a user diagram which will have a profile photo (picture schema)

my main concern is how i will perform the crud operations for user and blog schema as they have a subdocument picture which is a string but which must implement the upload with multer, cloudinary and fs. do I have to make two requests to create the document apart and its subdocument apart?

your help will be precious to me


Solution

  • You shouldn't make schemas like that. Everything related to the Blog should be in its schema so if the images are a part of the Blog then just add it inside the Blog's schema:

    const Blog = new Schema({
        title : String,
        description : String,
        images: Array
    });
    

    And then this images array can have the urls of the pictures of this one Blog. For the users part you should make another schema for users that has like username,password etc and profile picture for that user. This way things are more organized and readable not duplicating logic doesn't mean you should make it so modular that it becomes confusing. Keep it simple Everything related to Blog in the blog schema everything for Users in the User schema and so on.