Search code examples
mongodbmongoosemongoose-schemamongoose-populate

populate field in a subschema document


i have a nested subschema in form of an array, in this sub schema array i make reference of an object id of type Image(see image schema). what i want is to populate this object id with data of the image itself. to resume a want to populate a field in a sub schema document. I tried many solutions but without success, any idea how to achieve that? Thanks

i have 3 schemas like the following:

const deviceSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    name: {
        type: String,
        required: true,
    },
    os: {
        type: String,
        required: true,
    },
   },
    images:[assignedImagesSchema]
});

const  assignedImagesSchema = new mongoose.Schema({ 
    id: {type: mongoose.Schema.Types.ObjectId, ref:"Image"},
    isVisible: {
        type: Boolean,
        default: true
    },
    visibleFor: {
        type: Number,
        default: 0
    },
    orderIndex: {
        type: Number,
    }
  });
const imageSchema = mongoose.Schema({
    _id: mongoose.Schema.Types.ObjectId,
    url:{
        type: String,
        required: true,

    },
    orientation: {
        type: String,
        required: true,
    },
    devices: [{type: mongoose.Schema.Types.ObjectId, ref:'Device' }]

Solution

  • You could just add in your assignedImageSchema a new field that takes the imageSchema as an object. For example:

    const assignedImagesSchema = 
    new mongoose.Schema({ 
    image: { type: imageSchema } , 
    isVisible: { type: Boolean, default: true },
    visibleFor: { type: Number, default: 0 },
    orderIndex: { type: Number, } });