Moment.Js in my Nodejs app

Hi everyone,
When using moment js on my application, I need to show users how long ago a post was created. For example, it should read like this: Created 2h ago.
For now it gives the specific time the post was created, which I really don’t fancy. For example, it reads like this: November 5, 2020 9:37 PM.'/created-posts', (req, res) => {
    const timestamp = moment().format('LLL')
    req.body.created = timestamp
    db.collection('posts').insertOne(req.body, (err, result) => {
      if (err) return console.log(err)

This ‘created at’ value is being stored in a Mongdb database. Can anyone help on how I can make the database update itself, so the value can change with time.

The Mongodb snippet is as shown below:

"this is the body text"
"November 5, 2020 9:37 PM"

Unless I’m not understanding correctly, you don’t want to update the created timestamp in the DB, do you? What you want to do on the front end is subtract the created time from the current time and then format it the way you want.

1 Like

As said, why not calculate the “elapsed time” client-side, using the created time and current time?

1 Like

Thank you, let me do that

Thanks very much! I’ll do just that

I think doing it client-side is a reasonable solution, but I’m sure you can do it in the db as well using some of the built-in features. I’m not really much of an expert on MongoDB so I wouldn’t know exactly where to point you.

You might look at aggregation

Random example code

1 Like