Search code examples
node.jsmongodbaggregation-frameworkmatchmongoose-schema

how can i get an array after match query in mongodb aggregation


i am learning node js and mongodb , i have a schema of restaurants and a schema of orders with the restaurantId in every object . I am using match query in mongodb aggregation to get some orders where the restaurantId is equal to "restaurantId" , but the problem is that the result is a promise which i want to change to an array of objects to easily manipulate it . So can anyone help me ? this is the code :

 const orders = await Order.aggregate([
  {
    $match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
  }
])

i want use foreach function and other array functions on orders but i can't since the result is a promise , thank you .


Solution

  • First, let me point out that for a query this simple, there isn't even a need to use a aggregation. You can instated go with the plain old find.

    Having said that, In the specific example you provided, orders variable will actually be the array of matched orders due to the presence of await in front of the aggregate query. So long as you run that code inside an async function, the code should work just fine. Example:

    const somefunc = async () => {
      const orders = await Order.aggregate([
       {
         $match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
       }
      ]);
    
      console.log(orders); //will print an array of orders or [] if no orders are found.
    }
    

    Another way to run your code without asyncs and awaits is through the use of then. Example:

    const somefunc = () => {
      Order.aggregate([
       {
         $match:{ restaurantId: mongoose.Types.ObjectId(restaurantId)}
       }
      ])
       .then(orders => console.log(orders))
       .catch(e => console.log("error:", e))
    }
    

    So you are certainly correct in that Order.aggregate([...]) returns a promise. But you can resolve it by using await, which you already do, or then as pointed out above.