Reputation: 1477
I am trying to store my users age
on MongoDB
and i want to calculate the age
of the user dynamically and update it autonomously when possible.
I'm thinking of two approaches one is to store the date and on query use today's date as a reference and find the difference but the problem with this is the age
will not be updated on the schema in MongoDB
, how do i solve this?
The other is to set a hook for an API
and trigger that API
to update the details.
My schema looks something like this, though i am computing the age when saving it won't get updated as and when needed. Also as told taking today's date as a reference is affecting our analytics.
dateOfBirth: Date,
age: Number
Upvotes: 0
Views: 67
Reputation: 165
You can store as DOB and project age while querying using aggregation framework
db.getCollection('callmodels').aggregate([{
$project: {
name : 1,
email: 1,
age: {$trunc:{$divide: [ {$subtract: [new Date(), '$dob']},1000 * 60 * 60 * 24* 365]}}}
}
])
Upvotes: 1