猫鼬-使用Aggregate返回单个文档而不是文档数组 [英] Mongoose - Return a single document instead of an array of documents with Aggregate

查看:73
本文介绍了猫鼬-使用Aggregate返回单个文档而不是文档数组的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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.

我正在使用的查询:

  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
}

推荐答案

Aggregate方法返回一个数组;这是定义的行为.如果要使这种行为适应您的方式,则可以重新创建自己的聚合函数;也可以重新创建自己的聚合函数.或在每次调用时处理数组;像:

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

这篇关于猫鼬-使用Aggregate返回单个文档而不是文档数组的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆