Get total number of documents before applying cursor methods while using async/await in MongoDB?

Viewed 177

How can I get the total number of documents after using .find() and before applying .sort(), .skip(), and .limit()?

The object passed to .find() would eventually be generated from a query param,so the results for the count would be different each time. Should I be using promises instead of async/ await?

app.get('/', async (req, res) => {
  let pageSize = parseInt(req.query.limit) || 250;
  let page = parseInt(req.query.page) || 1;

  try {
    let products = await db.collection('Furniture')
      .find({})
      .sort({})
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .toArray();
    res.json({products});
  } catch (e) { console.log('Error sending products', e); }
});

A count property should be added to the json sent in the response with the total products that fit the find() parameters.

2 Answers

The cool thing about find(), sort(), skip(), and limit() is that they all return a cursor. This means they can be chained, but it also means at any step you can assign the cursor to a variable and run different functions on it and still have the cursor when you are done.

    let cursor = await db.collection('Furniture').find({})
    /* you want to wrap the following two in try catch as well, probably */
    let count = await cursor.count(); // do something with count then...

    let products = await cursor.sort({})
        .skip((page - 1) * pageSize)
        .limit(pageSize)
        .toArray();

The only way that I've done, it's make 2 queries, one for the counter and the other one for the products.

  try {
    let total = await db.collection('Furniture')
      .find({})
      .count();

    let products = await db.collection('Furniture')
      .find({})
      .sort({})
      .skip((page - 1) * pageSize)
      .limit(pageSize)
      .toArray();

    res.json({total, products});
  } catch (e) { console.log('Error sending products', e); }
Related