I wanna update time for post when user created post.
i tried some method but didnt get expected results.
Note - im storing created post in array. (locally)
const posts = [];
const addedDate = new Date();
const addedTime = addedDate.getMinutes();
exports.getIndex = (req, res, next) => {
res.render('index', {
pageTitle: 'NewsFeed',
path: '/',
post: posts,
time: addedTime,
});
};
exports.getPost = (req, res, next) => {
res.render('post', {
pageTitle: 'Create Post',
path: '/post',
});
};
exports.postAddPost = (req, res, next) => {
posts.unshift({ title: req.body.title });
res.redirect('/');
};
Here is the pic of post
time is not updating
i want to time auto update
like
1min ago - 1hr ago - 1 day ago
https://i.stack.imgur.com/eTD02.png
Use momentJS library. they have every format you'd need. The one you want is FromNow.
It seems like you create "addedDate" once when you run your application using the current time. When you show your news feed, you pass along the minutes of the time that you started your application.
I assume that you're trying to display when a post was created. In this case you should add the current time to your post object:
exports.postAddPost = (req, res, next) => {
posts.unshift({ title: req.body.title, added: new Date() });
res.redirect('/');
};
Then in your template you would iterate over the posts array that you pass as "post" and access the properties via "post.title" and "post.added".
I'm not sure what you had in mind regarding the minutes. If you intended to display something like "posted 5 minutes ago", then you could create another Date in your template and compare it with the "added" property of your post to figure out the difference.
The difference can be calculated fairly easily with vanilla JavaScript, you can just subtract two Date objects and get the difference in milliseconds:
const post = {
title: 'Title',
added: new Date(),
};
// some time later
const now = new Date();
const milliseconds = now - post.added;
const seconds = ms / 1000;
const minutes = seconds / 60;
And so on.
Related
I write a website using koajs and ejs template engine, I found I need to render a same year when access different route, like this:
router.get('/', async (ctx, next) => {
await ctx.render('index', {
currentYear: templates.currentYear, // <--this line will repeat many times
sub_title: 'Index',
}));
}).get('/notfound', async (ctx, next) => {
await ctx.render('404', {
sub_title: 'Not Found',
currentYear: templates.currentYear, // <--this line will repeat many times
});
})
can I get rid of it? I tried this way:
const templatesObject = {
currentYear: new Date().getFullYear(),
}
// use a addTemplate function to merge the template object
const addTemplate = (obj) => {return {...templatesObject, ...obj}}
// index
router.get('/', async (ctx, next) => {
await ctx.render('index', addTemplate({
sub_title: 'Index', // <-- now I need not to write currentYear many times
}));
})
but I wonder if I can have better way to solve it?
PS: the current year may be an example, it can be a website name, a user information, etc.
I'm coding a Discord bot in java script right now. I use MongoDB to store a "heat" value for every user in my server. (The "heat-system" adds a certain amount to a percentage whenever the user does something wrong and takes it off again after some time, to be more specific: -5 percent every minute in my example).
To do that, I want to use Model.updateMany() in a loop. As you see below, I used the filter parameter to find every document related to my server. The question now is how I can take these 5% off the stored value because it's not static, but dynamic.
const { Client } = require('discord.js');
const mongoose = require('mongoose');
//using modules and event handlers
module.exports = {
name: 'ready',
/**
* #param {Client} client
*/
async execute(client) {
const heatdb = require('/app/models/heatDB.js');
//how often the loop should pe repeated
const interval = 10 * 60 * 1000;
console.log('Client ready.')
//connnecting my data
mongoose.connect(
'I put the mongoose link here', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Data connected.')
}).catch((err) => {
console.log(err)
});
//loop begins here
setInterval(function(){
//filtered so that it's only searching for documents having the guild ID in it
heatdb.updateMany({ GuildID: "000000000000000000"}, {Heat: parseInt(/*needed value*/) - 5}})
}, interval);
},
};
And also see how my model is built below:
const { Schema, model } = require('mongoose');
module.exports = model("heatDB", new Schema({
GuildID: String,
UserID: String,
Heat: String,
}))
If you need anything else to help me, please let me know.
Thank you in advance,
Hydra
If your Heat value is a Number in Schema instead of String then you can try this-
heatdb.updateMany({ GuildID: "000000000000000000"},{$mul:{"Heat":0.95}})
Explanation:- you want to reduce Heat every time 5% percent then you can use mul
operator & set your heat value to 95% of current value. It will give you 5% deduction every time.
So I'm trying to retrieve multiple docs using Mongoose and render them using the HBS view engine. Unfortunatley, the only way I know how to render the view is to call res.render() inside the callback to the find() function used to retrieve documents from the MongoDB database. As such I can only retrieve one doc at a time and I'd like to know how to save multiple docs to variables and then render using res.render(). Anybody know how to do this? Router code below.
Basically, I'm pulling from multiple collections and want to know how to save the output of the find() function as variables and then pass them to the res.render() function to render it. You can see my hammed attempt below to save the results as variables which only returns a promise.
index.js:
var express = require('express');
var router = express.Router();
var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/test');
var Schema = mongoose.Schema;
var moment = require('moment');
var supportForumListSchema = new Schema({
title: String,
description: String,
numPosts: Number,
dateCreated: Date
}, {collection: 'support-forum-listing'});
var artworkForumListSchema = new Schema({
title: String,
description: String,
numPosts: Number,
dateCreated: Date
}, {collection: 'artwork-forum-listing'});
var supportForumList = mongoose.model('supportForumList', supportForumListSchema);
var artworkForumList = mongoose.model('artworkForumList', artworkForumListSchema);
tempDate = new Date(1542325638042);
currentDate = new Date(1542333003752);
console.log("current date:" + currentDate.toDateString());
tempHoursAgo = currentDate - tempDate;
tempHoursAgo = tempHoursAgo / (1000*60*60);
tempDateString = tempHoursAgo.toFixed(0); // could use Number(string) to convert back to number
console.log(tempDateString + "hours ago");
// temp new posts array
var newPosts = [
{postTitle: "Need help!", numViews: 1, datePosted: tempDateString},
{postTitle: "Unknown identifier", numViews: 0, datePosted: tempDateString},
{postTitle: "Messing up my normals", numViews: 3, datePosted: tempDateString},
{postTitle: "Anyone able to help?", numViews: 3, datePosted: tempDateString}
];
/* GET home page. */
router.get('/', function(req, res, next) {
artworkDoc = artworkForumList.find().then(function(doc){
return doc;
});
console.log(artworkDoc);
supportForumList.find().then(function(supportDoc){
res.render('index', { title: 'Home - 3D Artists Forum', headerTitle: "3D Artist Forums", supportForumList: supportDoc , artworkForumList: artworkDoc, latestPosts: newPosts});
});
});
module.exports = router;
Remember that requests are async calls, so you should chain then in order to get the desired result, otherwise " supportForumList.find()" might respond before artworkForumList.find()
Try this way
router.get('/', function(req, res, next) {
artworkDoc = artworkForumList.find().then(function(doc){
return doc;
}).then( doc => {
supportForumList.find().then(function(supportDoc){
res.render('index', { title: 'Home - 3D Artists Forum', headerTitle: "3D Artist Forums", supportForumList: supportDoc , artworkForumList: doc, latestPosts: newPosts});
});;
});
In this approach, supportForumList.find() is executed only when artworkForumList.find() has responded and you have data in the "doc" variable, and then that data is passed as a parameter.
Hope it Helps
Or same code with arrow function:
router.get('/', (req, res)=> {
artworkForumList.find()
.then(doc =>
supportForumList.find()
.then(supportDoc => res.render(title: 'Home - 3D Artists Forum', headerTitle: "3D Artist Forums", , { supportForumList: supportDoc, artworkForumList: doc, latestPosts: newPosts })))
}
I'm trying to query Mongo for all entries added today. For example, if I added something at 9 am, I only want that back and not something added at 9 pm last night.
I'm unsure how to properly format the query.
const db = require('../models');
const now = new Date();
const startOfToday = new Date(now.getFullYear(), now.getMonth(), now.getDate());
// Defining methods for the mealsController
module.exports = {
find(req, res) {
db
.Meal
.find({created_on: {$gte: startOfToday}})
},
findAll(req, res) {
db
.Meal
.find(req.query)
.sort({ date: -1 })
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
findById(req, res) {
db
.Meal
.findById(req.params.id)
.then(dbModel => res.json(dbModel))
.catch(err => res.status(422).json(err));
},
I can help you with a precise query if you share how you are storing data in db.
From your question, what i am guessing you are looking for is retrieving documents inserted after a certain time.
ObjectId.getTimestamp() will help you in this case. in Mongo, every insert has a time stamp associated with it. eg. ObjectId("5a6d75590827a11b6016f470").getTimestamp()
returned
ISODate("2018-01-28T07:01:45Z")
To get the Object id of a document, var a = db.collection.find(<condition>).toArray();a[0]._id then prints ObjectId("5a6d75560827a11b6016f46e")
so you can compare which documents were inserted after a certain date or time using this.
GL :)
models/category.js
var mongoose = require('mongoose');
// Category Schema
var categorySchema = mongoose.Schema({
title: {
type: String
},
description: {
type: String
},
created_at: {
type: Date,
default: Date.now
}
});
var Category = module.exports = mongoose.model('Category', categorySchema);
// Get Categories
module.exports.getCategories = function(callback, limit) {
Category.find(callback).limit(limit).sort([['title', 'ascending']]);
}
routes/categories.js
var express = require('express');
var router = express.Router();
Category = require('../models/category.js');
router.get('/', function(req, res, next) {
Category.getCategories(function(err, categories) {
if (err) res.send(err);
res.render('categories',
{
title: 'Categories',
categories: categories
});
});
});
router.post('/add', function(req,res) {
res.send('Form Submitted');
});
module.exports = router;
I got a few questions about this code
a) how does the callback mechanism work from routes/categories.js when we pass that callback function to models/category.js in Category.find(callback). That seems bizarre to me since we are doing a whole res.render which becomes part of Category.find() ?
b) Where is limit specified?
c) Why isn't there var in front of Category = require('../models/category.js');
a) that is indeed what happens, and is good: res.render will not get called until the find() operation executes on the database and a result is sent back for the mongoose code to return to you. You want to run the callback function after you get the result for your query, and so calling res.render before would be much more bizarre.
b) in the documentation. http://mongoosejs.com/docs/api.html#model_Model.find yields a Query object, which may be synchronously (i.e. before the query is actually made to resolve at the database) further specified with where, limit, etc.
c) because someone got lazy. In this example it doesn't actually make a difference because without var (or const or let in modern JS) a variable declaration is tacked onto the local context, which in your file is the routes/categories.js module context, and because Categories is declared at the top of that scope, var doesn't change where the variable ends up being bound. But it's lazy, and for good example code, that should have var in front of it.