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
}
}
])
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 .
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.
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);
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.
yes you can do it like for example
router.get('/something',async function(req, res, next) {
const data = await Model.aggregate([
{
$match: {
"id": id
}
}
])
}
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 :/
as for mongodb 4.4, aggregation is added with exec.
async function _(){
const data = await Model.aggregate([
{
$match: {
"id": id
}
}
]).exec();
return data
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With