Mongoose - Return a single document instead of an array of documents with Aggregate

前端 未结 1 358
后悔当初
后悔当初 2021-01-22 02:03

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 o

1条回答
  •  盖世英雄少女心
    2021-01-22 02:37

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

    0 讨论(0)
提交回复
热议问题