Babr
Babr

Reputation: 2081

How to define mongoose schema for an array of objects?

I'd like to make a mongoose schema to hold several photos of each user.

I know how to define the schema for a single photo:

const mongoose = require('mongoose');
  const Schema = mongoose.Schema;

   const PhotoSchema = new Schema({

    user: {
      type: Schema.Types.ObjectId,
      ref: 'users'
    }, 

    imgId :{
      type: Number,
    }

    isProfileImg: {
      type: Boolean,
      default: true,
    },

    visible: {
      type: String,
    },   

});


  module.exports = Photo = mongoose.model('Photo', PhotoSchema);

But I'm wondering how can I generalize the schema to hold multiple photos, each of which having the same fields as above (imagId, isProfilePImg and visible)?

Upvotes: 0

Views: 64

Answers (1)

Sashi
Sashi

Reputation: 2867

Try this schema:

const PhotoSchema = new Schema({

  user: {
    type: Schema.Types.ObjectId,
    ref: 'users'
  },
  photos: [
    {
      imgId: {
        type: Number,
      },
      isProfileImg: {
        type: Boolean,
        default: true,
      },
      visible: {
        type: String,
      }
    }
  ]
});

Upvotes: 1

Related Questions