1

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),
    }
  }
]);

1
  • Please mark answer as accepted in case if it worked for you Commented Aug 14, 2018 at 15:26

1 Answer 1

2

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),
    }
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.