Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose - Return a single document instead of an array of documents with Aggregate

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
}
like image 804
André Avatar asked Mar 05 '23 10:03

André


1 Answers

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(...);
});
like image 188
Orelsanpls Avatar answered Apr 08 '23 01:04

Orelsanpls