How to update javascript-times-ago in ejs file?

  ejs, express, javascript, mongoose, node.js

I am very new to node,ejs, and trying to build a blog-type website and display the posts time like "3 min ago or 4 months ago". So I used the javascript-times-ago. But clueless about how to update the posted time in every minute. I used setInterval but not working!

The home.ejs

<%- include("partial/head") %>
<div id="bdy">
 <% for (let post of posts){ %> 
<div class = "NewPost">
<p><%=post.description%></p>
<p id= "time" ><%=timeAgo.format((post.createdAt.getTime()),'mini')%></p> 
</div>
<% } %> 
</div>
<script>
    function mytime(){
        var p=timeAgo.format((post.createdAt.getTime()),'mini')
        document.getElementById("time").innerHTML= p || 'failed'
    }
    setInterval(mytime, 2000);
</script>
<%- include("partial/foot") %

index.js

const express = require("express");
const app = express();
const path = require('path');
const mongoose = require('mongoose');
const colors = require('colors');
const Posts = require('./models/post');
const time_ago = require('javascript-time-ago');
const en = require('javascript-time-ago/locale/en');
time_ago.addDefaultLocale(en);
const timeAgo = new time_ago('en-US');

app.get('/', async(req, res) => {
    const posts =  await Posts.find({});      
        res.render("home",{posts,timeAgo});
    
})

And is there any way to separate the script from the ejs file and get accessed to the database document?
Thanks.

Source: Ask Javascript Questions

LEAVE A COMMENT