POST HTTP Array: what am I doing wrong?

I’m trying to send an array over HTTP POST, it’s sending just an empty response. When I return the array to the console, it’s full. Any clue what’s going here?

exports = function() {
  const mongodbAtlas = context.services.get("mongodb-atlas");
  const auctions = mongodbAtlas.db("myFirstDatabase").collection("items");
  //Date now
  var now = new Date();
  //Get customer with last bid
  const findHighestBidder = auctions.aggregate([
    {$match: { $and: [ 
       {endDate: {$lt: now}}, 
       {status: "active" }
    ] }},
    { $project : { status: 1, bidHistory: 1 } },
    {$addFields : {bidHistory : {$reduce : {
        input : "$bidHistory", 
        initialValue : {bid : 0}, 
        in : {$cond: [{$gte : ["$$this.bid", "$$value.bid"]},"$$this", "$$value"]}}
    }}}
])
    const result = findHighestBidder.toArray

   //This returns the results as expected
    return result
   //This returns: "{ results: {} }"
    return context.http.post({
    url: "http://27b1e5a30df2.ngrok.io/api/stripe/test",
    body:  {result} ,
    encodeBodyAsJSON: true
  })
};

Hi @Al_B,

I think there is a fundamental issue in the code, as aggregate does not return an array but a promise…

So either you resolve it with .then syntax or use async in function declaration and await.

Further, I remember . toArray() with brackets.

Also is the body correct or there should be a field hosting array

{ Results : result}

Thanks
Pavel

Hi Pavel, I made the following changes. When I return the function, I get the array. When I return the POST method, the body is still empty.

const findHighestBidder = auctions.aggregate(pipeline).toArray()
    .then((results) => {
      return results
    })
    .catch(err => console.error(err))
    
    return findHighestBidder
    
    return context.http.post({
    url: "http://679339cf1551.ngrok.io/api/stripe/test",
    body:  {Results: findHighestBidder} ,
    encodeBodyAsJSON: true
  })

@Al_B,

Why do you have 2 returns without a condition…
This in itself does not allow the http call to happen.

More over , I think the http.call must be a part of the then() and not outside…

Thanks
Pavel

Very good thanks for the input.

I had two returns because I was testing both. I always commented out one when running the function.

This topic was automatically closed 5 days after the last reply. New replies are no longer allowed.