Rethinkdb query for data between 2 dates - rethinkdb

I would like to run a query that gets all the documents that have a lastUpdateDate from a date provided until today.
lastUpdateDated is defined like
lastUpdateDate = new Date() -> Tue Jan 19 2016 20:45:32 GMT+00:00
The following works in the RethinkDB Admin console
r.db('water').table('ground_water').filter(function (test) {
return test("lastUpdateDate").during(r.time(2015,1,1, 'Z'), r.now().date())
});
But here is the actual code (I have to do some processing on the date)
.table('ground_support_water_tests')
.filter(function(test) {
return test("lastUpdateDate").during(
r.time(2016,1,19, 'Z'),
r.now().date())
})
.run()
.then((results) => {
console.log(results);
done(null, results);
})
.catch((err) => {console.log(err); });
This returns no errors or results. I obviously like to not hardcode the date there so I have some logic to make a new r.time(yyyy,dd,mm) but that gives me the same results as this hardcoded one.

I think your query may contains some pitfalls.
First, I suggest you add rightBound: "closed" to option. Because you are comparing on date() and you don't care about time at all.
Second, I suggest you to change test("lastUpdateDate") -> test("lastUpdateDate").date() because you're removing time with date and it become Wed Jan 20 2016 00:00:00 GMT+00:00 while as your test("lastUpdateDate") is Wed Jan 20 2016 18:00:00 GMT+00:00 for example.
So let's try this:
.table('ground_support_water_tests')
.filter(function(test) {
return test("lastUpdateDate").date().during(
r.time(2016,1,19, 'Z'),
r.now().date())
}, {rightBound: "closed"})
.run()
.then((results) => {
console.log(results);
done(null, results);
})
.catch((err) => {console.log(err); });
Update:
I tried using NodeJS with official drive:
var r = require('rethinkdb')
r.connect().then(function(conn) {
r.table('t')
.filter((test) => {
return test("lastUpdateDate").date().during(r.time(2015,1,1, 'Z'), r.now().date(), {rightBound: "closed"})
})
.run(conn)
.then((cursor) => { return cursor.toArray() })
.then((data) => { console.log(data) })
})
On this date set:
[{
"id": "4917c8a1-1639-400c-964c-458d58b5bfcc" ,
"lastUpdateDate": Wed Jan 20 2016 21:12:51 GMT+00:00
}]
The query returns properly data.

Related

Lavarel don't accept Js Date format from Vue with axios, catch an 500 Internal Error

I have an Vue component, passing dates with axios requests.
I have an input where i introduce the date, for ex. ("2021-03-06"), it's working, but if i use an datePicker it's doesn't.
public function store()
{
$attributes = request();
Task::create([
'name' => $attributes['name'],
'client_id' => $attributes['client_id'],
'task_date' => $attributes['task_date'],
'state' => 1,
'type' => $attributes['type'],
'details' => $attributes['details'],
'invoiced_date' => $attributes['invoiced_date'],
'programing_worked_minutes' => $attributes['programing_worked_minutes'],
'support_worked_minutes' => $attributes['support_worked_minutes'],
'closed_date' => null,
]);
return 1;
}
<datepicker
v-model="task.task_date"
:lower-limit="new Date()"
placeholder="click here to choose a date"
id="task_date"
name="task.task_date"
class="block rounded p-0 shadow-inner border-gray-300 w-1/2"
required
/>
export default {
name: "addTask",
components: {
Datepicker
},
data() {
return {
task: {
name: null,
client_id: null,
task_date: null,
type: null,
details: null,
invoiced_date: null,
programing_worked_minutes: null,
support_worked_minutes: null,
},
message: "",
visual_spinner: false,
}
},
methods: {
sendData() {
this.message = '';
this.visual_spinner = true;
axios.post('/create-task', {
name: this.task.name,
client_id: this.task.client_id,
task_date: this.task.task_date,
type: this.task.type,
details: this.task.details,
invoiced_date: this.task.invoiced_date,
programing_worked_minutes: this.task.programing_worked_minutes,
support_worked_minutes: this.task.support_worked_minutes,
})
.then((response) => {
this.onSuccess();
})
.catch(function (error) {
console.log(error);
});
},
So, the request it working well, the problem is with the format Date ,
if is 2021-03-01 its working but if it's
Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time) not working
Thank you
If the problem is with the date format, you could format it into the expected format before submitting it to the database.
Once the JavaScript date format Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time) has been received by Laravel, you could format it using Carbon PHP library which already comes with the framework. i.e:
use Carbon\Carbon;
$javaScriptDateFormat = "Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time)";
$date = explode("(", $javaScriptDateFormat, 2)[0];
$formattedDate = Carbon::parse($date)->format('Y-m-d');
print_r($formattedDate); // "2021-03-13"
ADDENDUM
Another alternative is that you could use Moment.js to format the 'date string' got from datePicker Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time) into the expected format before sending it to the server. i.e:
import moment from "moment";
const date = new Date("Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time)");
console.log(moment(date).format("YYYY-MM-DD")); // 2021-03-13
Since Moment.js has been discontinued, as suggested by #AnuratChapanond, use Day.js instead as an alternative.
import dayjs from "dayjs";
const date = new Date("Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time)");
console.log(dayjs(date).format("YYYY-MM-DD")); // 2021-03-13
Sun Mar 07 2021 00:17:59 GMT+0600 (Bangladesh Standard Time) vs 2021-03-07 is not the same.
500 internal error means something happens on server side.
I guess, the problem is coming from your Laravel Database Schema
as example: $table->dateTime('task_date'); replace with $table->string('task_date');
Then migrate.
Finally i used
formatDate(date) {
var d = new Date(date),
month = '' + (d.getMonth() + 1),
day = '' + d.getDate(),
year = d.getFullYear();
if (month.length < 2)
month = '0' + month;
if (day.length < 2)
day = '0' + day;
return [year, month, day].join('-');
}
to convert
Sat Mar 13 2021 00:00:00 GMT+0200 (Eastern European Standard Time)
into 2021-03-13

"Date has wrong format" Angular 10 Rest Django

Hi I'm new to these two frameworks and I need your help !
So I'm using Rest Django for backend and Angular for Frontent , I'm also using Angular material for the DatePicker , although I changed the format of the date to YYYY-MM-DD to the DatePicker I still receive an error message "Date has wrong format. Use one of these formats instead: YYYY-MM-DD." by the server when sending the api !
to change the date format in Angular I used this code into app.module
import { DateAdapter, MAT_DATE_FORMATS, MAT_DATE_LOCALE } from '#angular/material/core';
import { MomentDateModule, MomentDateAdapter } from '#angular/material-moment-adapter';
export const DateFormats = {
parse: {
dateInput: ['YYYY-MM-DD']
},
display: {
dateInput: 'YYYY-MM-DD',
monthYearLabel: 'MM YYYY',
dateA11yLabel: 'LL',
monthYearA11yLabel: 'MM YYYY',
},
};
providers: [
{ provide: DateAdapter, useClass: MomentDateAdapter, deps: [MAT_DATE_LOCALE] },
{ provide: MAT_DATE_FORMATS, useValue: DateFormats }
],
After console.log('date',this.date) to see the date object entered by the datepicker I received
date
{…}
​
_d: Date Tue Aug 18 2020 00:00:00 GMT+0100 (UTC+01:00)
​
_i: Object { year: 2020, month: 7, date: 18 }
​
_isAMomentObject: true
​
_isUTC: false
​
_isValid: true
​
_locale: Object { _calendar: {…}, _longDateFormat: {…}, _invalidDate: "Invalid date", … }
​
_pf: Object { empty: false, overflow: -1, charsLeftOver: 0, … }
​
<prototype>: Object { add: createAdder(val, period), calendar: calendar$1(time, formats), clone: clone(), … }
Do you know how can I solve the problem please ?
u should create a method to trim ur date removing the timezone & other inform then call the method in ur date input field
something like this
yourDateApp.component.ts file
trimDate(myDate){
let strDate = JSON.stringfy(myDate.value)
let newDate = strDate.substring(1, 11)
//assign the new trimmed date to date value in ur form
yourForm.controls['date_field'].setValue(newDate)
}
yourDateApp.component.html file
//call your function in the html file like this
<input matInput (dateChange)="trimDate($event)">
this will accept the date trim it to a way django will recognize it

.getField() returning empty result

Using the RethinkdbDash package for Node.js and Rethink, I'm able to use this ReQL:
r.db('<DATABASE>').table('<TABLE>').get('<UUID_FOR_OBJECT>')
...to get the desired object out of the database with the following format...
{
"address": "<ADDRESS>" ,
"createdAt": Thu Sep 15 2016 02:08:54 GMT+00:00 ,
"email": <EMAIL>,
"firstName": "<FIRST NAME>" ,
"fullName": "<FULL NAME>" ,
"lastName": "<LAST NAME>" ,
"middleName": "<MIDDLE NAME>" ,
"phone": "<PHONE NUMBER>" ,
"prescriptions": [
{
"expiresOn": Thu Sep 15 2016 00:00:00 GMT+00:00 ,
"hasExpired": false ,
"name": "<MEDICATION NAME>" ,
"prescribedBy": "<DOCTOR NAME>" ,
"prescribedOn": Thu Sep 15 2016 02:54:52 GMT+00:00 ,
"startOn": Thu Sep 15 2016 02:54:52 GMT+00:00 ,
"uuid": "f11fed84-30dc-4cf9-af36-b715f303bed1"
}
] ,
"uuid": "bd4d6d44-3af3-4224-afef-d7e9a876025b"
}
The problem comes when I try to add the pluck or getField function to the query to isolate and retrieve just the 'prescriptions' array. This is the function in my controller for the call...
export function all(req, res) {
let id = req.params.id
r.table('Patients').get(id).pluck('prescriptions').run() //Also tried .getField('prescriptions') and .get(id)('prescriptions')
.then((results) => {
console.log(results)
return res.json({ status: 200, data: results })
})
.catch((error) => {
console.log(error)
return res.json({ status: 400, message: 'There was an error finding the medication of patient ' + id, data: error })
})
}
When I call the API path the access this data and execute the all function, I get the following response...
{
status: 200,
data: []
}
The exact same query, however, works as expected within the Rethink admin console's data explorer.
Any idea or help as to why this is happening is greatly appreciated!
Problem solved.
Issue was actually with my routes specified with Express and nothing to do with rethinkdb!

Sort by Formatted DateTime with Kendo UI DateSource

In an attempt to create a list sortable by date, I created the following datasource:
sort: { field: 'dateTime', dir: 'asc' },
schema: {
model: {
id: 'Id',
fields: {
dateTime: {
field: 'DateTime',
type: 'Date',
parse: function (value) {
return kendo.toString(kendo.parseDate(value), 'MM/dd/yyyy hh:mm tt');
}
},
stuff: 'Stuff'
}
}
}
After filling it with data, I noticed that the rows in the bound list were sorting alphabetically like:
01/02/2015 08:22 PM
12/12/2014 09:00 PM
12/18/2014 08:22 PM
How can I get these dates to sort in ascending chronological order?
I imagine this occurred because the value was converted to a string in the parse function so it was no longer sorting like a date so I removed the parsing code from the field:
sort: { field: 'dateTime', dir: 'asc' },
schema: {
model: {
id: 'Id',
fields: {
dateTime: {
field: 'DateTime',
type: 'Date'
},
stuff: 'Stuff'
}
}
}
This reverted the dates shown in the listview to the default format: (Fri Dec 12 2014 21:00:00 GMT-0500 (Eastern Standard Time)), but it now sorted correctly. The final piece of the puzzle is to instead bind my element to a calculated property that parses the date instead of the dateTime field like so:
HTML
<!-- The element: -->
<td data-bind="html: myDate" style="width: auto;"></td>
JavaScript
// And in the observable:
myDate: function(e) {
return kendo.toString(kendo.parseDate(e.dateTime), 'MM/dd/yyyy hh:mm tt');
}
This worked like a charm and I got this:
12/12/2014 09:00 PM
12/18/2014 08:22 PM
01/02/2015 08:22 PM
Optionally, if you have a DateTimePicker bound to your dateTime property your myDate calculated property will not update when you change it. I solved this by listening for the change and triggering the change event manually:
viewModel.bind('change', function (e) {
if (e.field == 'selectedEvent.dateTime') // or whatever your property comes out as
viewModel.trigger('change', { field: 'myDate' });
});

How to iterate through all the fields of an object

I have an object that has about 23 columns. Is there a way to iterate through each column automatically? Rather than specifically selecting each column using .get("COLUMN_NAME") ?
Thanks guys.
That's say a Class A -- with fields' id, createdAt, updatedAt, a, b, c and obj is an instance of A.
obj.attributes is an object which hold a, b, c and id, createdAt, updateAt are properties of obj.
The following is an example to show all fields' name except special field (id, createdAt, updatedAt) in web console.
Object.keys(obj.attributes).forEach(function(fieldName) {
console.log(fieldName);
});
To be more simple :
object.get('COLUMN_NAME') is equivalent to object.attributes.COLUMN_NAME
So if you do a console.log(object.attributes) you will have a JS Object as example :
{
"cheatMode":true
"createdAt":Tue Oct 30 2018 10:57:08 GMT+0100 (heure normale d’Europe centrale) {} (this is a JS Date object)
"playerName":"Sean Plott"
"score":1337
"updatedAt":Tue Oct 30 2018 12:18:18 GMT+0100 (heure normale d’Europe centrale) {} (this is a JS Date object)
}
With all attributes and their values.
That's all.
Full example code of ParseServer Query
const GameScore = Parse.Object.extend("GameScore");
const mainQuery = new Parse.Query(GameScore);
mainQuery.equalTo("cheatMode", true);
mainQuery.find().then(async (response) => {
response.map(function(object){
console.log(object.attributes)
// Will log for example :
// {
// "cheatMode":true
// "createdAt":Tue Oct 30 2018 10:57:08 GMT+0100 (heure normale d’Europe centrale) {} (this is a JS Date object)
// "playerName":"Sean Plott"
// "score":1337
// "updatedAt":Tue Oct 30 2018 12:18:18 GMT+0100 (heure normale d’Europe centrale) {} (this is a JS Date object)
// }
})
});

Resources