I'm new to mongo and tried to return the result of an aggregation.
joinById: (collection, id, $lookup, res) => {
var $match = {"_id": ObjectId(id) };
MongoClient.connect(url, function (err, db) {
if (err) throw err;
var dbo = db.db("myDB");
dbo.collection(collection)
.aggregate([{ $match }, { $lookup }])
.toArray(function (err, result) {
if (err) throw err;
const jsonable = stringify(result);
res.status(200).json(jsonable)
db.close();
});
});
}
I did it work at this first step but I needed to change something, because I cant figure how to return the result to the calling function.
So I did this change:
joinById2: async (collection, id, $lookup) => {
const $match = {"_id": ObjectId(id) };
const client = await MongoClient.connect(url);
const table = client.db("myDB");
const collect = table.collection(collection);
const aggregate = collect.aggregate([{ $match }, { $lookup }]);
const result = aggregate.toArray()
return stringify(result);
},
Now I can return the value but ... The aggregate dont give any results.
I prefere the second way to write it, and already changed other function that are working. So I'd like to know: Why cant I get the same result ? How can I fix this ?
CodePudding user response:
I just missed the Promise.
const result = await aggregate.toArray()
With an await it works !
CodePudding user response:
You need to await for Promises
async (collection, id, $lookup) => {
const $match = {"_id": ObjectId(id) };
const client = await MongoClient.connect(url);
const table = await client.db("myDB");
const collect = await table.collection(collection);
const aggregate = await collect.aggregate([{ $match }, { $lookup }]);
const result = await aggregate.toArray()
return stringify(result);
}