John Marquez
John Marquez

Reputation: 645

Mongodb $addFields, return field value from function?

I am storing in my mongodb collection the video id of a video served in the cloud. When my front end makes an API call for that video, I want to return the formatted URL based on that video id. I have a function that does this, but I can't get it to work with $addFields in and aggregate pipeline:

My documents look like this:

{
    "date" : ISODate("2018-03-30T00:00:00.000+0000"), 
    "title" : "Tips and Tricks", 
    "video_id" : "13966740", 
}

...and I want my API call to return them with an extra field, "image_url":

{
    "date" : ISODate("2018-03-30T00:00:00.000+0000"), 
    "title" : "Tips and Tricks", 
    "video_id" : "13966740", 
    "image_url" : "https://myhostingservice.com/13966740/preview_image", 
}

This is what I'm trying in models/video.js:

const hostingservice = require('myhostingservicehelperfunctions');

module.exports.getVideo = function (callback) {
    videoCollection.aggregate(
        [
            { $match: { } },
            { $addFields: {
                    image_url: hostingservice.createImageURL("$video_id")
                }
            },
            { $sort: {
                'date' : -1 }
            }
        ],
        callback);
};

The helper function simply takes the string param and returns a string.

myhostingservicehelperfunctions.js:

module.exports.createImageURL = function ImageURL(video_id){
    return 'https://myhostingservice.com/' + video_id + '/preview_image';
};

My front end receives all the correct data, but the value of image_url is "https://myhostingservice.com/$video_id/preview_image", which makes me think my function ran, but it was passed the actual string "$video_id", not the value of the key, video_id. Look closely, the URL contains "$video_id", not "13966740" from the example above.

What am I doing wrong here?

Upvotes: 2

Views: 1550

Answers (1)

Elvis
Elvis

Reputation: 1143

You can't concatenate strings like that in mongoDB aggregation, you'll need to concatenate strings using the concat operator, so the function "createImageURL" should look something like this,

module.exports.createImageURL = function ImageURL(){
    return { $concat: [ "https://myhostingservice.com/", "$video_id", "/preview_image" ] };
};

Upvotes: 1

Related Questions