Reputation: 11
I want to call a function in mongodb query. Is there any way to do such thing or is there any other way to do that
Example:
const imageUrl = function(imageName) {
const urlParams = {Bucket: 's3-bucket/uploads', Key: imageName};
s3bucket.getSignedUrl('getObject', urlParams, async function (err, url) {
console.log('imageUrl', url);
});
}
const feedTest = await Feed.aggregate([
{
$project: {
_id: 1,
feedImage: imageUrl(feedImage),
}
}
]);
Upvotes: 1
Views: 468
Reputation: 542
You can't execute a function as part of mongo query, but you can pass the result there. The problem is that you would need to make your query inside of the callback. But that can be managed with promises and async/await:
const imageUrl = function(imageName) {
const urlParams = {Bucket: 's3-bucket/uploads', Key: imageName};
return new Promise((resolve, reject) => {
s3bucket.getSignedUrl('getObject', urlParams, (err, url) => {
if (err) {
reject(err)
} else {
resolve(url)
}
})
})
}
const feedTest = await Feed.aggregate([ {
$project:{
_id: 1,
feedImage: await imageUrl(feedImage),
}
}
Upvotes: 2