0

My data stored for user is in the following format :

{
  name: 'XYZ',
  email: 'abc@gmail.com',
  password: 'encrypted',
  categories: [
    {
      name: 'category1',
      type: 'type1',
    },
    {
      name: 'category2',
      type: 'type2',
    }
  ],
  transactions: [
    {
      date: 2020-04-09T06:00:30.000Z,
      type: 'type1',
      category: 'category1',
      description: 'some desc',
    },

    {
      date: 2020-04-08T06:00:30.000Z,
      type: 'type2',
      category: 'category1',
      description: 'some desc',
    },

    {
      date: 2020-04-07T06:00:30.000Z,
      type: 'type3',
      category: 'category1',
      description: 'some desc',
    }
  ]
}

I want to get the data of particular user after providing unique email but along with that I want transactions filtered between 2 dates. Example I want data of user with email = abc@gmail.com and transactions of dates between 2020-04-08 and 2020-04-09.

Sample output looks like this :

{
 name: 'XYZ',
 email: 'abc@gmail.com',
 categories: [...],
 transactions: [
    {
      date: 2020-04-09T06:00:30.000Z,
      type: 'type1',
      category: 'category1',
      description: 'some desc',
    },

    {
      date: 2020-04-08T06:00:30.000Z,
      type: 'type2',
      category: 'category1',
      description: 'some desc',
    }]
}

Or only transactions between the given dates for the given user email is also fine.

Tried using this query

User.aggregate([
    {$match: {email: email}},
    {$unwind: '$transactions'},
    {$match: {'transactions.date': {$gt: startDate, $lt: endDate}}},
    {
      $group: {
        _id: '$_id',
        transactions: {
          $type: "$transactions.type",
          $category: "$transactions.category",
          $date: "$transactions.date",
          $description: "$transactions.decription"
        }
      }
    }
  ]).exec((err, data) => {
    if (err) throw err;
    console.log(data);
  })

Getting the error as follows The field 'transactions' must specify one accumulator

Tushar Tambe
  • 115
  • 1
  • 8

0 Answers0