Home > Net >  Mongoose and MongoDB, how to create relation betwean two models with multiple references?
Mongoose and MongoDB, how to create relation betwean two models with multiple references?

Time:07-12

everyone.

So I have this "blog" app where users can create posts with images. How my app works is that it loads different posts by userID. So I have a relation bewtean user and post by the user and post _id, however I also want to save username into the post schema and created ralation that way. Is it possible to do such thing ?

This is my User schema

    import mongoose from "mongoose";
    import mongooseUniqueValidator from "mongoose-unique-validator";
    
    const Schema = mongoose.Schema;
    const validator = mongooseUniqueValidator;
    
    const user_Schema = new Schema({
            username: { type: String, required: true, unique: true },
            email: { type: String, required: true, unique: true },
            password: { type: String, required: true, minlength: 3 },
            user_image: { type: String },
            posts: [{ type: mongoose.Types.ObjectId, required: true, ref: 'Post'  }], //relation bewtean post and user
    
        },{ timestamps: true }
        );
    
    user_Schema.plugin(validator);
    
    
    export const USER: mongoose.Model<any> = mongoose.model("User", user_Schema);

And this is my Post Schema:

import mongoose from "mongoose";

const Schema = mongoose.Schema;

const post_Schema = new Schema({
        title: { type: String, required: true, },
        description: { type: String, required: true, },
        imageURL: { type: String },
        creator_id: { type: mongoose.Types.ObjectId, required: true, ref: 'User'  }, 
    },
    { timestamps: true }
    );

export const POST: mongoose.Model<any> = mongoose.model("Post", post_Schema);

However this is what I want the post to contain, I want the post to contain ID of the user who created it and the name of the user who created it. However I do not know how to create it. So this is how I want my Post schema to look like, I want to be able to save both the user ID and username into the post.

const Schema = mongoose.Schema;

const post_Schema = new Schema({
        title: { type: String, required: true, },
        description: { type: String, required: true, },
        imageURL: { type: String },
        user: {
            creator_id: { type: mongoose.Types.ObjectId, required: true, ref: 'User'  }, //relation bewtean post and user
            creator_name: { <soemthing here>, ref: 'User'  }, //relation bewtean post and user
        },
        
    },
    { timestamps: true }
    );

export const POST: mongoose.Model<any> = mongoose.model("Post", post_Schema);

CodePudding user response:

If you want to retrieve the creator name using the ref is the correct approach, you just need to populate the Post documents when you are retrieving them with:

const posts = await Post.find({}).populate('creator').exec()

for (const post of posts) {
    // Every post should contain the creator user properties
    console.log(post.creator._id, post.creator.username)
}

Just make sure that your ref fields are of type mongoose.Schema.Types.ObjectId:

const post_Schema = new Schema(
    {
      title: { type: String, required: true },
      description: { type: String, required: true },
      imageURL: { type: String },
      creator: { type: mongoose.Schema.Types.ObjectId, required: true, ref: 'User' },
    },
    { timestamps: true }
  );
  
  export const POST: mongoose.Model<any> = mongoose.model('Post', post_Schema);
  • Related