Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to use async/await with mongoose aggregate

I am using async/await in my node applications when I use find() commands but is it possible to do the same with aggregations?

Something like

const data = await Model.aggregate([
      {
         $match: {
            "id": id
         }
      }
])
like image 349
RUEMACHINE Avatar asked Oct 16 '18 13:10

RUEMACHINE


People also ask

Does Mongoose support async await?

Mongoose queries are not promises. They have a . then() function for co and async/await as a convenience. If you need a fully-fledged promise, use the .

How do you use await With mongoose?

To use async-await syntax, you need to write an asynchronous function, as shown below: const mongoose = require('mongoose'); const server = '127.0. 0.1:27017'; // REPLACE WITH YOUR OWN SERVER const database = 'test'; // REPLACE WITH YOUR OWN DB NAME const connectDB = async () => { try { await mongoose.

How do you populate with aggregate?

With the latest version of mongoose (mongoose >= 3.6), you can but it requires a second query, and using populate differently. After your aggregation, do this: Patients. populate(result, {path: "patient"}, callback);

What is Mongoose aggregate?

Mongoose's aggregate() function is how you use MongoDB's aggregation framework with Mongoose. Mongoose's aggregate() is a thin wrapper, so any aggregation query that works in the MongoDB shell should work in Mongoose without any changes.


3 Answers

yes you can do it like for example

router.get('/something',async function(req, res, next) {
const data = await Model.aggregate([
      {
         $match: {
            "id": id
         }
      }
])
}
like image 84
Omega Cube Avatar answered Nov 05 '22 06:11

Omega Cube


Try this instead

const agg = Model.aggregate([
      {
         $match: {
            "id": id
         }
      }
])

const data = await agg.exec()

This worked for me, Omega Cube's answer didn't :/

like image 33
lelbil Avatar answered Nov 05 '22 06:11

lelbil


as for mongodb 4.4, aggregation is added with exec.

async function _(){
   const data = await Model.aggregate([
   {
      $match: {
         "id": id
      }
     }
   ]).exec();
   return data
}
like image 23
gogog Avatar answered Nov 05 '22 06:11

gogog