Prasanth Bendra
Prasanth Bendra

Reputation: 32790

Concatenate a string while populating

Here is my code to populate albums and their images :

server.get(url_prefix + '/image', function(req, res, next) {
        var album_id = req.query.album_id
        Album.findOne(
                {_id : album_id}
             )
             .populate('images')
             .exec(function (err, album) {
                if (album) {
                    return res.send({
                        status: {
                            error: 0,
                            message: "Successful"
                        },
                        data: {
                            album: album
                        }
                    })
                } else
                    return notify_error(res, "No Results", 1, 404)
             })


    })

Album schema :

var AlbumSchema = new Schema(
{
    userId:{ 
        type: String, 
        trim: true
    },
    albumName:{ 
        type: String, 
        trim: true
    },
    albumDescription:{ 
        type: String, 
        trim: true
    },
    imageCount:{ 
        type: Number,
        default: 0
    },
    timestamp:{ 
        type: String, 
        trim: true
    },
    albumThumbnail:{ 
        type: Object
    }, 
    images : [{ 
                type: Schema.Types.ObjectId, 
                ref: 'Image' 
              }
    ]
})

Image schema :

var ImageSchema = new Schema(
{
    _album : { type: String, ref: 'Album' },
    imageName:{ 
        type: String, 
        trim: true
    },
    imageDescription:{ 
        type: String, 
        trim: true
    },
    timestamp:{ 
        type: String, 
        trim: true
    },
    imageURL:{ 
        type: String, 
        trim: true
    },
    imageURLSmall:{ 
        type: String, 
        trim: true
    },
    imageThumbnailURL:{ 
        type: String, 
        trim: true
    },
    likeCount:{ 
        type: Number,
        default: 0
    },
    commentCount:{ 
        type: Number,
        default: 0
    },
    userLike:{
        type: Boolean,
        default: false
    }
})

I am able to populate the albums and their images, In image schema imageURL contains only the image name (image.jpg) so while retrieving I want it to be like http://localhost/assets/profile/image.jpg I have to do it while populating the data or before sending the data, because this API s are used by mobile devices so they need the full path to show the image.

So how can I add a string to a field in mongodb while populating the data ?

Thanks in advance

Upvotes: 1

Views: 747

Answers (1)

Mattias Farnemyhr
Mattias Farnemyhr

Reputation: 4238

Try this:

ImageSchema
    .post('init', function(obj) {
        var url = 'http://localhost/assets/profile/'
        obj.imageURL = url + obj.imageURL
    })

This function will be executed every time you grab an object from the database.

Upvotes: 1

Related Questions