Search code examples
javascriptnode.jsmongodbmongoosemongoose-schema

How to make a virtual object in a subcollection - Mogoose


In mongoose I have an object ('target') with an image (name+ext.). Each object ('target'). has a sub-collection of other objects that again contains an image (name+ext).

Now I have been able to create a virtual for the target.image. So i get a full location URL. But I am unable to create a virtual for target.upload.image.

How can I do that?

const targetSchema = mongoose.Schema({
    title: {
        type: String, required: true
    },
    userId: {
        type: String, required: true
    },
    ........
    image: {
        type: String, required: true
    },
    uploads: [{
        upload_image: {
            type: String, required: true
        },
        upload_userId: {
            type: String, required: true
        },
    }],
});

This is my virtual for my target image

targetSchema.virtual('targetImgURL').get(function(){
    let url = process.env.URL + ":" + process.env.PORT + "/public/images/targets/uploads/" + this.image
    return url
});

Solution

  • Yes i have found the solution. Unfortunately, it is impossible to detain everything at once. But this way is not extra cumbersome. See the code below for the solution.

    const uploadSchema = mongoose.Schema({
        upload_image: {
            type: String, required: true
        },
        upload_userId: {
            type: String, required: true
        },
    });
    
    // Virtuals
    uploadSchema.virtual('UploadImgURL').get(function(){
        let url = process.env.URL + ":" + process.env.PORT + "/public/images/targets/answers/" + this.image
        return url
    });
    
    const targetSchema = mongoose.Schema({
        title: {
            type: String, required: [true, 'A title is required']
        },
        ....
        uploads: [ uploadSchema ],
    });
    
    // Virtuals
    targetSchema.virtual('targetImgURL').get(function(){
        let url = process.env.URL + ":" + process.env.PORT + "/public/images/targets/uploads/" + this.image
        return url
    });