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)
// }
})
});
Related
I'm currently using mongoTemplate via Spring boot and my data structure is:
I wrote the following code to get only the comments list in the db.
MatchOperation matchOperation = Aggregation.match(
Criteria.where("_id").is(new ObjectId(postId))
);
ProjectionOperation projectionOperation = Aggregation.project()
.and("comments").as("comments");
Aggregation aggregation = Aggregation.newAggregation(matchOperation, projectionOperation);
AggregationResults<Object> result = mongoTemplate.aggregate(aggregation, PostEntity.class, Object.class);
result.getMappedResults().forEach(System.out::println);
The contents of System.out::println are as follows.
{
_id=618b37bfb6196619dbe35abb,
comments=[
{
_id=618b65c64d04820f90565c70,
writer=617a2d81c4033d1358e2ffba,
nickname=test user,
createDate=Wed Nov 10 15:25:10 KST 2021,
content=qwer,
replies=[],
likes=[]
},
{
_id=618b66784d04820f90565c71,
writer=617a2d81c4033d1358e2ffba,
nickname=test user2,
createDate=Wed Nov 10 15:28:08 KST 2021,
content=asdf,
replies=[],
likes=[]
},
{
_id=618b67d54d04820f90565c72,
writer=617a2d81c4033d1358e2ffba,
nickname=test user3,
createDate=Wed Nov 10 15:33:57 KST 2021,
content=asdf,
replies=[],
likes=[]
},
...
]
}
The data is imported fine, but I don't know how to process it. I want to create a CommentDto object and put the above output comments list in List<CommentDto>, how should I do it?
You could also retrieve it as a List:
Aggregation aggregation = Aggregation.newAggregation(lookUp, match1, unwindPrices, unwindTags, unwindIndex, match2, groupOperation);
List<ProductVo> list = mongotemplate.aggregate(aggregation ,"products", ProductVo.class).getMappedResults();
When you run the query you are mapping to Object. Just change the output object type to your dto:
AggregationResults<CommentDto> result = mongoTemplate.aggregate(aggregation, PostEntity.class, CommentDto.class);
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
How should I delete my associations in with soft delete?
I have the following structs
type PrivateGormModel struct {
ID uint `gorm:"primaryKey" json:"id,string"`
CreatedAt time.Time `json:"-"`
UpdatedAt time.Time `json:"-"`
DeletedAt *time.Time `gorm:"index" json:"-"`
}
type Relation struct {
PrivateGormModel
OwnerID uint `json:"ownerID"`
OwnerType string `json:"ownerType"`
Addresses []Address `gorm:"polymorphic:Owner;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"addresses"`
Contacts []Contact `gorm:"polymorphic:Owner;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"contacts"`
People []Person `gorm:"polymorphic:Owner;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"people"`
BankAccounts []BankAccount `gorm:"polymorphic:Owner;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"bankAccounts"`
}
type Company struct {
PrivateGormModel
Name string `json:"name"`
Relation Relation `gorm:"polymorphic:Owner;constraint:OnUpdate:CASCADE,OnDelete:CASCADE;" json:"relation"`
}
I left out the adress, contact, person and bankaccount struct to keep this post short but they are simple structs with a OwnerID and OwnerType. And the following handler
func DeleteCompany(db *database.Database) fiber.Handler {
return func(c *fiber.Ctx) error {
id, err := IDFromParams(c)
if err != nil {
return c.JSON(responseKit.ParameterMissing())
}
toDelete := new(model.Company)
result := db.Preload("Relation.Addresses").
Preload("Relation.Contacts").
Preload("Relation.People").
Preload("Relation.BankAccounts").
Preload(clause.Associations).
First(toDelete, id)
fmt.Printf("\n%v", toDelete)
result = db.Select("Relation.Addresses").
Select("Relation.Contacts").
Select("Relation.People").
Select("Relation.BankAccounts").
Select("Relation").
Debug().
Delete(toDelete)
if result.Error != nil {
return c.JSON(responseKit.RecordDeleteError())
}
return c.JSON(responseKit.RecordDeleteSuccess())
}
}
Where the print outputs
{PrivateGormModel:{ID:5 CreatedAt:2021-01-15 11:24:03.672857 +0100 CET UpdatedAt:2021-01-15 11:24:03.672857 +0100 CET DeletedAt:<nil>} Name:Test Relation:{PrivateGormModel:{ID:5 CreatedAt:2021-01-15 11:24:03.738351 +0100 CET UpdatedAt:2021-01-15 11:24:03.738351 +0100 CET DeletedAt:<nil>} OwnerID:5 OwnerType:companies Addresses:[{PrivateGormModel:{ID:5 CreatedAt:2021-01-15 11:24:03.739322 +0100 CET UpdatedAt:2021-01-15 11:24:03.739322 +0100 CET DeletedAt:<nil>} OwnerID:5 OwnerType:relations Country:AA Zip:1111AB Number:1 Addition: Street:Test State:Test City:Test}] Contacts:[{PrivateGormModel:{ID:5 CreatedAt:2021-01-15 11:24:03.740319 +0100 CET UpdatedAt:2021-01-15 11:24:03.740319 +0100 CET
DeletedAt:<nil>} OwnerID:5 OwnerType:relations Tel:0612345678 Mail:test#test.com URL:}] People:[] BankAccounts:[{PrivateGormModel:{ID:5 CreatedAt:2021-01-15 11:24:03.740319 +0100 CET UpdatedAt:2021-01-15 11:24:03.740319 +0100 CET DeletedAt:<nil>} OwnerID:5 OwnerType:relations Bank:test BIC:test IBAN:test AccountHolder: Establishment:test}]}}
and the debug debugs the following
DELETE FROM "relations" WHERE "relations"."owner_type" = 'companies' AND "relations"."owner_id" = 5
DELETE FROM "companies" WHERE "companies"."id" = 5
So the relation is deleted. But it isn't doing anything for the hasMany relation. I read this
https://gorm.io/docs/associations.html#Delete-with-Select
And tried to do that since the constrains don't seem to do anything, but nothing seems to work and delete the adresses, contacts, people and bank accounts. How am I supposed to soft delete all the relationships of Company?
I've tested this with the latest version of Gorm, and Select and Delete only works for first-level associations.
So if you did
db.Select("Relation").Delete(toDelete)
You'd see that both Company and Relation get their DeletedAt set to the current timestamp.
To achieve soft-deletion of the second-level relations, you'd need to delete those in a separate call:
db.Select("Addresses", "Contacts", "People", "BankAccounts").Delete(toDelete.Relation)
// or more compactly
db.Select(clause.Associations).Delete(toDelete.Relation)
It may also be worthwhile asking yourself whether soft-deleting just the root of the model tree, and leaving everything else as-is isn't sufficient for your usecase.
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
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.