0

As the title says

consider dummy data like this (some users in my mongoose database)

[{ name : "ahmed" , registeredIn : 1590739626724 },
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }
{ name : "ahmed" , registeredIn : 1590739626724 }]

in my admin panel , I'd like to return a chart which display number of registered users per each month

just need numbers , 2 in May , 3 in June and so on..

what's the quickest solutions ?

the only solution in my mind now is a bit bad

to fetch each month separately

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

fetch users between timestamp X & Y

what if I want to fetch about 20 months , will I call the MongoDB 20 times ?

is there any more better solution ?

Community
  • 1
  • 1
27mdmo7sn
  • 53
  • 1
  • 6
  • Have you tried grouping by month in your query?...https://stackoverflow.com/questions/27366209/mongodb-group-by-month#answer-27366497 – bloo May 29 '20 at 08:21
  • 1
    you could use mongoose.aggregate to find data you could use $match and pass your filter object, along with it you can pass timestamp with gt and lt operator. Then you can group them based on month. MongoDB is known for its aggregation and this is the best and fastest way to achieve what you are looking for. – Suresh Shetiar May 29 '20 at 08:26
  • I searched in your answers , but still confused , maybe a direct answer will help better – 27mdmo7sn May 29 '20 at 09:04

1 Answers1

0

try using momentJS

npm install moment --save   # npm
yarn add moment             # Yarn

then when you create new user add a new prop in your mongoose schema for creation date

var UserSchema = new mongoose.Schema({
   // your fields
   creation_date:{type:String}
})
UserSchema.methods.preSaveMethod = function(){
 this.creation_date = moment().format('MMMM Do YYYY, h:mm:ss a');
}
UserSchema.pre("save", preSaveMethod);

although you can discard moment library here but it is much easier to use it than regex for example if you want to get a month earlier try

moment().subtract(1, 'months').format('MMM YYYY');

hope I made it clear enough for you

Ibrahim shamma
  • 399
  • 5
  • 13
  • Thanks Ibrahim for your help , however looks your answer did not answer my question , how to get the counts of every month (check this question similar to my needs) : https://stackoverflow.com/questions/41791015/mongoose-group-and-count – 27mdmo7sn May 29 '20 at 09:13
  • if you saved the creation date you can make User.find() based on that month moment().isBetween(Date1,Date2) – Ibrahim shamma May 29 '20 at 09:30
  • Sorry , but this will lead to my bad solution , if read my question well – 27mdmo7sn May 29 '20 at 16:44