Before starting to use aggregate in order to create a timestamp of the document, I was using findOne so I could get a single object but now I'm getting an array with a single object. Is it possible to make the query return a single object instead of an array? Thank you in advance.
Query that I'm using:
News.aggregate()
.match({ '_id': n })
.project({ 'title': true, 'text': true, 'timestamp': { '$subtract': ['$date', new Date('1970-01-01')] } })
What is returning:
[
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
]
What I'd like to get returned:
{
"_id": "5b9650beae847b1e5866cace",
"title": "Notícia 2",
"text": "Texto da Notícia 2",
"timestamp": 1543807353257
}
Aggregate
method returns an array; this is the defined behavior. If you want to adapt this behavior to your way, you can either re-create your own aggregate function; or deal with the array at every call; like :
async function aggregate(model, func) {
const aggregateObject = func(News.aggregate());
const ret = await aggregateObject.exec();
// Deal with the fact there is no answer
if (ret && ret.length) {
return ret[0];
}
return false;
}
const directData = await aggregate(News, (aggregateObj) => {
return aggregateObj
.match(...)
.project(...);
});
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