Search code examples
node.jsmongoosemongoose-schema

Mongoose schema with field of an array of other schemas


first of all, I am a beginner and currently, I am working on a social media blog type. Now, I have my userSchema and postSchema models:

USER MODEL

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please insert your name'],
  },
  email: {
    type: String,
    required: [true, 'Please insert your email'],
    unique: true,
    lowercase: true, //transform into lowercase / not validator
    validate: [validator.isEmail, 'Please provide a valid email'],
  },
  avatar: {
    type: String,
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user',
  },
  password: {
    type: String,
    required: [true, 'Please provide a password'],
    minLength: 8,
    select: false,
  },
  passwordConfirm: {
    type: String,
    required: [true, 'Please confirm your password'],
    validate: {
      validator: function (el) {
        return el === this.password;
      },
      message: 'Passwords are not the same',
    },
  },
  passwordChangedAt: Date,
  posts: [] // ???????????????
});

POST MODEL

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'A post must have a title'],
  },
  author: {
    type: String,
    required: [true, 'A post must have a title'],
  },
  likes: {
    type: Number,
    default: 10,
  },
  comments: {
    type: [String],
  },
  image: {
    type: String,
  },
  postBody: {
    type: String,
    required: [true, 'A post must contain a body'],
  },
  createdAt: {
    type: Date,
    default: Date.now(),
    select: false,
  },
});

Now I don't know if it's the best approach but I was thinking of having a field in userSchema with the type of an array of postSchema so I will have for each user their own posts created. Can I do that? If not how I can achieve that? Should I use search params fields to filter posts by the author? I am really confused how I should approach this situation. Thank you guys


Solution

  • Check out this example

    const UserSchema = new mongoose.Schema({
        username: String,
        posts: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Post'
        }]
      })
    
    const PostSchema = new mongoose.Schema({
        content: String,
        author: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User'
        }
      })
    
    const Post = mongoose.model('Post', PostSchema, 'posts');
    const User = mongoose.model('User', UserSchema, 'users');
    
    module.exports = { User, Post };
    
    

    Credit: https://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7