Query Mongo for all entries added today (newbie) - javascript

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 :)

Related

how to update posted time locally in node.js

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.

Mongoose sorting by createdAt

I have a getPosts controller on my Post Controller, my goal is to sort it by the createdAt time to maintain order because when I map it on the frontend it starts from the last created to the latest.
const getPosts = asyncHandler(async (req, res) => {
const posts = await Post.find().sort([createdAt, 1]);
res.json(posts);
});
sort() can't take arrays it either takes string or an object
const posts = await Post.find().sort({createdAt: 1});
also you can use " asc "," ascending " instead of 1.
You can use mongo query sort() to get that. It can take value 1 or -1 according to sorting order, you can read mongo db document for more here.
Also you can put this sort query in timestamp of these for getting this too.
//Sorting by descending order
const posts = await Post.find().sort({ createdAt: -1 })
//Sorting by ascending order
const posts = await Post.find().sort({ createdAt: 1 })
So you can do this:
const getPosts = asyncHandler(async (req, res) => {
const posts = await Post.find().sort({ createdAt: 1 })
res.json(posts)
})
sort() takes in either an Object or a String.
the correct syntax should be
const posts = await Post.find().sort({createdAt: 1});

Sequelize delete query runs, but does not resolve Promise

I have a node js server that is creating and deleting from database using Sequelize. When i create new user in "Users" table, query normally runs and server returns response. But when i try to delete user from "Users" table, query runs but promise isn't resolved, therefore i get no response from server. Here is
my code:
const { User } = require("./models")
const user = {id: "...."} //Parsed delete request from client, id is not undefined
User.destroy({
where: {
id: user.id,
},
})
.then(res.status(200).clearCookie("refresh-token"));
.catch(res.status(400));
What i see in console:
Executing (default): DELETE FROM "Users" WHERE "id" = '6d3edbab-03b8-429b-b249-a9d3ba6bce7a'
And after a while:
DELETE /api/user/delete - - - - ms [2021-3-14 14:17:11]
I delete stuff from other tables too and they work, so it seems that Users table is somewhat special. Whats wierd is that when i look in database i see that record was deleted. I have no idea what is happening.
Thanks for help!
I solved my issue by creating a new function that opens a new Sequelize connection and
uses that to delete records in db. Here it is:
function deleteUsr(id, res) {
const { Sequelize } = require("sequelize");
if (!/^([0-9a-z]){8}-([0-9a-z]){4}-([0-9a-z]){4}-([0-9a-z]){4}-([0-9a-z]){12}$/.test(id)) {
res.status(400).send("Provide valid UUID")
}
const seq = new Sequelize(
"connection string"
);
seq
.authenticate()
.then(console.log("yipeee"))
.catch(err => console.error(err));
seq
.query(`delete from "Users" where id='${id}'`)
.then(x => {
res.status(200).clearCookie("refresh-token").send(x);
seq.close();
})
.catch(err => {
res.status(400).send(err);
seq.close();
});
}
Avoid using this function if your input isn't sanitized properly, because anyone who is signed could delete any user if using this. I am taking uuid from verified jwt access token and comparing it to encrypted refresh token, so that user cannot even input anything into the function.
Hope it helped!

cannot do multiple query indexed firestore collection

so i tried to get data from firebase using this function
getData(){
const startDate = this.$store.state.inputFilter.rangeDate.start
const endDate = this.$store.state.inputFilter.rangeDate.end
db.collection(this.inputType)
.where('idAlat', '==',this.equipment)
.where('tanggal', '>=', startDate).where('tanggal', '<=', endDate)
.where('project', '==', this.project)
.get().then(docs => {
docs.forEach(doc => {
console.log(doc.data().tanggal.toDate(), doc.data().idAlat)
})
})
}
but then every time i try to run the fucntion, it shows error like this in console:
but then i follow the link and do the instruction to create composite index in firebase like this:
Is there something wrong i did? Thanks!
PS: word 'tanggal' means 'date' in english

Get all docs by a given date ? (createdAt)

I have this date given by a date picker widget:
let targetDate = '2019-01-12';
All my documents have a createtAt date generated by timestamps:
"createdAt": "2019-01-12T21:49:05.546Z"
I want to get all documents that field createdAt matches with my given date.
I tried using $elemMatch:
const allDailies = await Daily.find({ createdAt: { $elemMatch: dateTarget } });
const allDailies = await Daily.find({ createdAt: { $elemMatch: { from: dateTarget, to: dateTarget} } });
And no one works, how can I do this query? Actually I can't modify my Schema :(
EDIT:
router.get('/daily/:date', async (req, res) => {
try {
const targetDate = new RegExp(`^${req.params.date}`);
const allDailies = await Daily.find({ createdAt: { $regex: targetDate } });
console.log('Dailies', allDailies);
return res.json({ allDailies });
} catch (error) {
return res.sendStatus(httpStatus.INTERNAL_SERVER_ERROR);
}
});
It returns a 500 error
Convert your targetDate to the same type as createdAt and use it on query as tatgetDate. Not dateTarget as you use it now (you typed it wrong).
You have to convert your target date in to ISODate format. But this will be taken care by mongoose by default so.. What you want to do is change your query like this
Model.find({createdAt:{$gte:params.frm, $lte:params.to}},callback);
or if you want to just give a single date try like this
Model.find({createdAt:dateTarget},callback);

Categories

Resources