且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

猫鼬-使用Aggregate返回单个文档而不是文档数组

更新时间:2023-02-18 13:56:19

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