4

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
}
4
  • 2
    Aggregate always returns result in form of array you have to take the 0th index from it. No other option Commented Sep 14, 2018 at 11:20
  • thanks @AnthonyWinzlet Commented Sep 14, 2018 at 11:28
  • $unwind operator will help here... Commented Sep 14, 2018 at 11:46
  • $unwind works with array fields in a document only, not with whole array of results. @wrangler Commented Sep 14, 2018 at 11:59

1 Answer 1

8

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(...);
});
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.