【问题标题】:Mongoose - Return a single document instead of an array of documents with AggregateMongoose - 返回单个文档而不是使用 Aggregate 的文档数组
【发布时间】:2019-02-19 04:44:53
【问题描述】:

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

我正在使用的查询:

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

返回的是什么:

[
    {
        "_id": "5b9650beae847b1e5866cace",
        "title": "Notícia 2",
        "text": "Texto da Notícia 2",
        "timestamp": 1543807353257
    }
]

我想退货:

{
    "_id": "5b9650beae847b1e5866cace",
    "title": "Notícia 2",
    "text": "Texto da Notícia 2",
    "timestamp": 1543807353257
}

【问题讨论】:

  • 聚合总是以数组的形式返回结果,你必须从中获取第 0 个索引。没有其他选择
  • 感谢@AnthonyWinzlet
  • $unwind 运营商将在这里提供帮助...
  • $unwind 仅适用于文档中的数组字段,而不适用于整个结果数组。 @牧马人

标签: node.js mongodb mongoose


【解决方案1】:

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(...);
});

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2017-04-17
    • 2020-08-17
    • 2014-09-20
    • 2012-06-08
    • 2015-08-23
    • 1970-01-01
    相关资源
    最近更新 更多