Mongoose - 使用 Aggregate 返回单个文档而不是一组文档

And*_*dré 4 mongoose mongodb node.js

在开始使用聚合来创建文档的时间戳之前,我使用了 findOne 以便我可以获得单个对象,但现在我获得了一个包含单个对象的数组。是否可以使查询返回单个对象而不是数组?先感谢您。

我正在使用的查询:

  News.aggregate()
    .match({ '_id': n })
    .project({ 'title': true, 'text': true, 'timestamp': { '$subtract': ['$date', new Date('1970-01-01')] } })
Run Code Online (Sandbox Code Playgroud)

什么返回:

[
    {
        "_id": "5b9650beae847b1e5866cace",
        "title": "Notícia 2",
        "text": "Texto da Notícia 2",
        "timestamp": 1543807353257
    }
]
Run Code Online (Sandbox Code Playgroud)

我想得到的回报:

{
    "_id": "5b9650beae847b1e5866cace",
    "title": "Notícia 2",
    "text": "Texto da Notícia 2",
    "timestamp": 1543807353257
}
Run Code Online (Sandbox Code Playgroud)

Gré*_*EUT 7

Aggregate方法返回一个数组;这是定义的行为。如果您想根据自己的方式调整这种行为,您可以重新创建自己的聚合函数;或在每次调用时处理数组;喜欢 :

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(...);
});
Run Code Online (Sandbox Code Playgroud)