loopback equal to date is not working - node.js

I am new to loopback. I have a date column start_date with DATE datatype.
when i try to fetch data with greater than or less than operations on start_date is working, but when i tried to fetch data equal to a date its not working:
the following is my fetching part:
Its working:
app.models.goals.find({where: {
start_date: {gt:'2016-03-31'}
}}, function(err, res) {
});
Its not working:
app.models.goals.find({where: {
start_date: '2016-03-31'
}}, function(err, res) {
});
Data is there in DB for 2016-03-31, but empty response. Is any syntax error.please help me to solve this.

I don't think there is anything wrong with the syntax. I tried the same syntax in both Strongloop API Explorer and with loopback Node.JS API and found it to be working.
However, While checking these out, I noticed that when the date string doesn't have time and TZ information in it, the time portion is assumed to be 00.00.00 in the local timezone. For example, when I used the following code on my "Sandbox" model:
Sandbox.find({where: {myDateProp:'2016-04-2'}}, function(err, res){
console.log('results are %j', res);
next();
});
The retrieved results record contained:
Retreived results are [{"myStringProp":"String5","myDateProp":"2016-04-01T18:30:00.000Z","id":"56fc1dc6b9de1a6b06750b98"}]
Notice that my search for 2016-04-2 actually matched a record with date 2016-04-01 6:30 PM which is the GMT equivalent of 2016-04-2 00:00:00 IST.
I am guessing that this may have something to do with the behaviour that you observe. I'd recommend you to check the Date value of start_date of the record in the database. Then, if necessary add the time and timezone information to the filter in your code.

Related

how to save value of formarray in mysql with nodejs

I have a problem and I want someone to help me.
My English is not that good, I'm sorry about that I'll try my best to explain the problem to you hopefully u can help me and thank you.
I'm working on an activity management platform where an employee login to his account and chose a project, then a table contains the days of a certain month under each day there is an input where he enters 1 or 0 if he worked that day or not this is how the UI looks:
When he clicks the button VALIDER (Validate in French) the data entered should be saved in mysql database.
to collect the data I used FormBuilder in angling, I defined as a form group that contains a form control that should get the name of the project, a form control that gets the month, and one for the year, and a form array that should get the values of the 3 inputs, when I console.log the value of the form I get this:
when I try to save the data in my database, I get the message successful, but when I look at my database nothing gets stored,
my database contain a table with :
projectName: varchar(45),
month: number,
year: number,
days: JSON
I think that the problem is that days are an array and not of type Jason because I tried saving an array, but I did like this: insert into project (projectName, days) values ('nomProjet', '['0', '0', '0']') and it gets saved but my days Array doesn't.
my node js code for the backend :
app.post('/cra/add', function (req, res) {
let nomProjet = req.body.projet;
let year = req.body.year;
let month = req.body.month;
let days = req.body.days;
if (nomProjet && year && month && days) {
connection.query('INSERT INTO projetcra2 ( nomProjet, month, year, days ) SET ( ? , ? , ? , ?) ',
[nomProjet, month, year, days],
function (error, results, fields) {
res.send({ status: 'success' , days});
res.end();
});
} else {
res.send({ status: 'failed', message: 'some data are required', loggedin: false });
res.end();
}
});
my formbuilder :
my save function to save to the database :
addDaysWorked() {
this.api.cra(this.form.value).subscribe(
(data: any) => {
console.log(data);
}, (error: HttpErrorResponse) => {
console.log(error);
}
)
}
when i test with postman :
my database :
I hope my problem is explained, if u think I can help with anything else let me know and thank you.
I'm not an expert at backend stuff by any means. However, I believe storing items as an array is inside of a single column in a database is not ideal. You should consider creating a new, separate table, for just days worked.
In the table, you could have a column that specified the date, whether or not he/she worked, and link obviously link this using a foreign key (like userId) to the users table or the main table in this case.
This would allow you to more easily insert the data. Since each day would just be a simple row, querying would also be simpler as you would just query data given a Timeframe (example: from beginning of August - End of August), a user (unique user ID).
Here are a couple other generic stack questions that might clarify as well.
Hope this helps!
Check out this resource as well

Get data between two date from sql server

I want to get all data between two dates from sql server with using mssql and query of sequelize in nodejs.
Start and End dates come from react frontend with axios.post.
For example start date is 2021-01-04T08:53:00.000Z and end date is 2021-01-05T21:00:00.000Z in express.
app.post('/getData', function (req, res) {
let startTime=req.body.start
let endTime=req.body.end
sequelize.query(` select Date_Time from S001T01 where Date_Time between ${startTime} and ${endTime}`, {
type: sequelize.QueryTypes.SELECT
}).then(result => {
console.log(result)
})
});
It returns many error, one of them is UnhandledPromiseRejectionWarning: SequelizeDatabaseError: Invalid column name '2021-01-05T21:00:00.000Z 23:59:00'..
In table viewer Date_Time column shown like that
I don't know what should I do.
Thanks for help.
You might have a wrong datetime format. 2021-01-05T21:00:00.000Z 23:59:00 doen't correspond to the traditional ISO 8601.
If you want all entries between 2021-01-04T08:53:00.000Z and 2021-01-05T21:00:00.000Z, your SQL query should look like this :
select Date_Time from S001T01 where Date_Time between 2021-01-04T08:53:00.000Z and 2021-01-05T21:00:00.000Z
You should also consider using modified datetime instead on concatenation.
Maybe something like thing should do the job :
var dt = new Date();
dt.setHours( dt.getHours() + 2 );
I hope it helped you.

Node.js with TypeORM inserts wrong timezones into Azure SQL Database

I have a backend written on top of node.js, I'm using TypeORM as the ORM and Azure SQL Database to store my data. When I call the ORM's create() and save() functions, I'm passing in the correct date and time as can be seen below. But when I query the inserted data in the server, the timezone has shifted from -03:00 to +00:00. It maybe a normal behavior, since I'm new working with dates though.
This is the code where I call the create() in:
class CreateAppointmentsService {
public async execute({ provider, date }: RequestDTO): Promise<Appointment> {
const appointmentsRepository = getCustomRepository(AppointmentsRepository);
const roundDate = startOfHour(date);
const foundAppointment = await appointmentsRepository.findByDate(roundDate);
if (foundAppointment) {
throw Error('This date and time already has a booking.');
}
const appointment = appointmentsRepository.create({
provider,
date: roundDate,
});
await appointmentsRepository.save(appointment);
return appointment;
}
}
This is my debug information, showing date and time in expected timezone.
This is the data in the database. The field type is datetimeoffset and the server time is set to UTC (+00:00).
Thanks in advance! =)
[EDIT]: Explaining better: the time I posted to the database is rounded to 20:00 -03:00 (America/Sao_Paulo/Brasilia). If you look the column "created_at", the time is updated to UTC, but the column "data" only got the timezone set to +00:00, the time remais 20:00.
Found the problem! I forgot to set the "date" column to datetimeoffset in the typeORM model =(.
How it was:
#Column()
date: Date;
Changed to:
#Column('datetimeoffset')
date: Date;
Now it work wonders! The correct timezone is being set alongside the time. Cheers!

node js compare mongodb database time and current time of a server

I have the code below updating offers_status to 'expired' if date stored on a mongodb database is old than current system/server time;
dbo.collection("offers").updateMany({older_date_in_DB:{$lt: current_system_time},
{$set:
{offerStatus:"EXPIRED"}},
(err,response)=>{
if(err) throw err;
console.log(response.modifiedCount)
})
However, i notice that if the current date is say 10/18/2019 and older_date_in_db is say 08/01/2019,the query above doesn't update the offer status to 'EXPIRED'. I don't understand why?
A date like 10/15/2019 updates the status to "EXPIRED" while a date like "08/01/2019" doesn't.
Please use following line for compare date condition in mongodb
{ older_date_in_DB: { $lt: new Date('10/18/2019') } }
if value is dateFormat then use new keyword

NodeJS saving date to MongoDB using Moment

I'm trying to save a date to MongoDB using MomentJS. I want to save the current date/time plus 1 hour. To do this I use the following code (I'm using seconds as this number will be pulled from an API which gives a number in seconds, once I get the basics sorted I will change the 3600 to a variable):
var expire = moment().add(3600, 's').format();
User.update({email: req.user}, {$set: {expire: expire}}, function(err, update) {
if(err) throw err;
});
If I console.log the value for expire it shows the time with 1 hour added as expected. The issue is that what it saved in my DB is the current time WITHOUT the hour added to it.
Any help would be greatly appreciated.
In mongodb, the comparing time is supposed to use utc time and Date obj.
Because var expire = moment().add(3600, 's').format(); return a string not obj.
You should transform it to a Date obj so that mongodb can know it.
What you have to do is very easy.
var expire = moment().add(3600, 's').format().toDate()
In fact, if you want to compare time in mongo with gt and lt , I suppose you change the time to utc. let time = moment().utc(yourTime, "YYYY-MM-DD HH:mm:ss").toDate()
Tell mongoDB about the change by using doc.markModified('pathToYourDate').
const Assignment = mongoose.model('Assignment', { dueDate: Date });
Assignment.findOne(function (err, doc) {
doc.dueDate.setMonth(3);
doc.save(callback); // THIS DOES NOT SAVE YOUR CHANGE
doc.markModified('dueDate');
doc.save(callback); // works
})
See full details here: https://mongoosejs.com/docs/schematypes.html#dates

Resources