How do I get all objects with a specific start date - javascript

I'm trying to use a date parameter that comes in through the request and return all objects that have that date. I do not want to look at the time stamp, just the year, month, day.

The following in the controller file of mongoose finds dates that match a specific day:
export const getBookingByDate = (req, res) => {
Booking.find({start: {$gt: req.params.bookingDate}}, (err, booking) => {
if(err){
res.send(err);
}
res.json(booking);
})
}

Related

How to convert MYSQL Timestamp to CST time with Javascript?

If someone could help me with this I´d appreciate it!
I need to convert MYSQL Timestamp 2022-09-14T05:08:32.000Z to my local time (Central Standard Time) and then be able to pass that result to EJS. I am passing the data to my EJS view with this route, but not sure how to convert this timestamp before passing it to EJS.
This screenshot shows the 'rows' values which are being passed to EJS.
rutas.get('/historial', loggedIn, async (req, res, next) => {
await pool.query('SELECT * FROM historial WHERE id = ? AND calidaddeltrade = ? OR calidaddeltrade = ?', [req.user.id, 'Excelente', 'Buena'], function (err, rows, fields) {
if (err) { throw err };
res.render('./historial', { rows: rows});
console.log(rows);
})
});
Does anyone know how could I do this with Javascript? Thanks!!

Sending Emails at Specific Time/Date with NodeJS from values in React App

My current ReactJS application enables users to be able to submit time, date and text values, which is posted to a NodeJS backend.
Here is my current NodeJS code:
app.post("/send", function (req, res) {
let mailOptions = {
from: `${req.body.vals.email}`,
to: process.env.EMAIL,
subject: 'SUBJECT INFO',
html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`,
};
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
res.json({
status: "fail",
});
} else {
console.log("email sent");
res.json({
status: "success",
});
}
});
});
I want to be be able to schedule the emails to be sent at the given values of time and date from the front-end ReactJS.
I have tried to use node-schedule but the whole date/time threw me off.
Edit:
This is the current date and time format that comes back.
date: 2022-08-28
time: 14:07
[edit: current solution not working]
app.post("/send", function (req, res) {
let mailOptions = {
from: `${req.body.vals.email}`,
to: process.env.EMAIL,
subject: 'SUBJECT INFO',
html: `${req.body.vals.date} ${req.body.vals.time} ${req.body.vals.info}`,
};
const dateParsed = new Date(`${req.body.vals.date}T${req.body.vals.time}Z`)
schedule.scheduleJob(dateParsed, function(){
transporter.sendMail(mailOptions, function (err, data) {
if (err) {
res.json({
status: "fail",
});
} else {
console.log("email sent");
res.json({
status: "success",
});
}
});
})
});
I don't understand the problem with node-schedule
The API allows you to use date object instead of cron
const schedule = require('node-schedule');
const date = new Date(2012, 11, 21, 5, 30, 0);
const job = schedule.scheduleJob(date, function(){
console.log('The world is going to end today.');
});
Dates
Easiest way I can think of:
const date = '2022-08-28'
const time = '14:07'
console.log(new Date(`${date}T${time}Z`))
But I'm not sure if it's best
Also, it will always give UTC time instead of local
Usually, dates are sent from the frontend as ISO already.

How to send multiple query results from backend to frontend in node

I am making a simple check-in and check-out system for employees. In the main panel I want to show the number of hours worked per day and in another field the weekly total.
I can now show the hours per day in a table, the problem comes when I have to show the total since I make that query to the database with another query.
With the following code I perform the query and perform a render in the index view using the EJS templates.:
router.get('/', (req, res) => {
const week = DateTime.now().weekNumber;
conexion.query('SELECT * FROM assistance WHERE week = ?', week, (error, results) => {
if(error){
throw error;
}else{
res.render('index', {results: results});
}
})
});
With this code I perform the query of the total hours. but I don't know how to show it in the same index view since it is a separate query from the first one:
conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week, (error, results) => {
if(error){
throw error;
}else{
return('index', {totalHours: results});
}
})
In this way I am trying to receive the information in the index view with EJS:
<div>
<div>Total hours:<%= totalHours%></div>
</div>
Use try/catch async-await, then just do both queries.
router.get('/', async(req, res) => {
const week = DateTime.now().weekNumber
try {
// query 1
const totalHours = await conexion.query('SELECT time_format(SUM(TIMEDIFF(a.exit, a.entry)), "%H:%i") AS hours from assistance a WHERE a.week = ?', week)
// query 2
const results = await conexion.query('SELECT * FROM assistance WHERE week = ?', week)
res.render('index', {
totalHours,
results
})
} catch {
res.render('error-page')
}
})

Creating new mongoose sub-doc and appending to existing parent doc

I'm building a website with a database using NodeJS, MongoDB, Express, Mongoose etc.
I have two schema set up: Events and a sub-doc schema Categories (among others).
The function pulls in array which contains the data needed to create several categories (this bit works) as well as the Event ID appended to the end.
The first few bits below just grab that ID, then remove it from the array (probably a better way to do this, but again, it works).
As mentioned above, the Categories then create correctly (and even do validation), which is amazing, BUT...
They don't get appended to the Event doc. The doc updates the "categories" field to an applicable number of "null" values, but I cannot for the life of me get it to actually take the IDs of the newly created categories.
I nabbed (and adjusted) the below code from somewhere, so this is where I'm at...
exports.addCategories = catchAsync(async (req, res, next) => {
const categories = req.body;
const length = categories.length;
const eventID = categories[length - 1].eventId;
categories.pop();
Event.findOne({ _id: eventID }, (err, event) => {
if (err) return res.status(400).send(err);
if (!event)
return res.status(400).send(new Error("Could not find that event"));
Category.create(categories, (err, category) => {
if (err) return res.status(400).send(err);
event.categories.push(category._id);
event.save((err) => {
if (err) return res.status(400).send(err);
res.status(200).json(category);
});
});
});
});
Currently the mongoose debug output is showing the following (which confirms that MOST of it is working, but the IDs just aren't being pulled correctly):
> Mongoose: events.updateOne({ _id: ObjectId("614bc221bc067e62e0790875")}, { '$push': { categories: { '$each': [ undefined ] } }, '$inc': { __v: 1 }}, { session: undefined })
Nevermind! I realised that "category" was still an array, rather than an element of the categories array as I'd assumed.
So I replaced that section with this, and now... it works!
Category.create(categories, (err, categories) => {
if (err) return res.status(400).send(err);
categories.forEach((category) => {
event.categories.push(category._id);
});
event.save((err) => {
if (err) return res.status(400).send(err);
});
});

NodeJs insert current Datetime field into MySQL db

I'm trying to insert a DATETIME field into my MySQL db.
var dt = require('moment')().format('YYYY-MM-DD HH:mm:ss');
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id],
[dt],
(error, results, fields) => {
}
);
I get this error:
C:\Users\tiger\Desktop\prova\REST_API_WITH_MYSQL-master\node_modules\mysql\lib\protocol\Parser.js:437
throw err; // Rethrow non-MySQL errors
^TypeError: this._callback.apply is not a function
If I try this code, everything comes right:
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,"2021-01-27 00:00:00")`,
[results[0].id],
//[dt],
(error, results, fields) => {
}
);
What i'm doing wrong?
You have your parameters in 2 separate arrays. Put your parameters in the same parameter array.
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, dt],
(error, results, fields) => {
}
);
The correct format probably is YYYY-MM-DD HH:MM:SS(I think it depends on MySQL configuration, but this is the default) as the docs points out.
So you should try using moment's format() method like this:
const myDate = moment(data.myTime.format('YYYY/MM/DD HH:mm:ss')).format("YYYY-MM-DD HH:mm:ss");
pool.query(
`insert into login(id, id_utente, data_login) values(NULL,?,?)`,
[results[0].id, myDate],
(error, results, fields) => {
}
);

Categories

Resources