im trying insert in multiple tables.
let me explain User create a new client, client insert id into bill - (idClient) table
this is the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"services": [1, 2, 3],
"bill":{
"description": "New project"
}
}
the insert
_service.create = async (client) => {
const { description } = client.bill;
try {
const data = await Client.create(
{ client, bill: { description: description } },
{ include: { model: Bill } }
);
return data.id;
} catch (err) {
handleError = err.hasOwnProperty("errors")
? err.errors.map((error) => error.message)
: err;
throw new Error(handleError);
}
};
but im getting this error
{
"name": "Error",
"message": "ReferenceError: description is not defined"
}
and yes, bill table has that column.
the relation
Client.hasOne(models.Bill, { foreignKey: "idClient" });
so, im stuck, i read the documentation and i trying to do the same way as they do but i dont know what i doing wrong
https://sequelize.org/master/manual/creating-with-associations.html
I already did, i dont know if the best way
i modified the payload
{
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"description": "new Proyect",
}
the insert query, change bill to Bill as my table name and then add description value
const { description } = client;
const data = await Client.create(
{ ...client, Bill: { description } },
{ include: { model: Bill } }
);
and the result
{
"id": 6,
"name": "Evelyn",
"lastName": "Doe",
"phone": "4534534",
"email": "eve#hotmail.com",
"identification": "xxxxx",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z",
"Bill": {
"id": 4,
"idClient": 6,
"totalAmount": null,
"description": "new Proyect",
"idStatus": 2,
"createdAt": "2020-11-13T08:52:37.000Z",
"updatedAt": "2020-11-13T08:52:37.000Z"
}
}
Related
I am trying to map the data in React that is coming from the API but I am having problems mapping the object that contains dots for example this: name.en_US.
What is the proper way to map this object and keeping the data structure that I have?
I am getting the date in this format from the API:
{
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
},
And then I am trying to map it using the following code.
const {
user,
employeeId,
businessCustomer,
endCustomer,
device,
task
} = task;
const{
endCustomerName,
address,
place
} = endCustomer;
const {
shipmentIds,
names
} = device;
const{
en_US,
fi_FI
} = names;
const {
time,
duration,
summa
} = task;
const data = {
"user": "User",
"employeeId": "0000",
"businessCustomer": "customer",
"endCustomer": {
"name": "",
"address": "",
"place": ""
},
"device": {
"shipmentIds": "23",
"name.en_US": "wasi",
"name.fi_FI": " masi"
},
"task": {
"time": "2019-02-10T16:55:46.188Z",
"duration": "00:00:24",
"sum": "75€"
}
};
const { device } = data;
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
const nameUS = device['name.en_US'];
console.log(name_en_US, nameUS);
Use [ ] notation like, device['name.en_US'] .
You can destructure your propery as #Vishnu mentioned, or you could also destructure it by providing a valid key name
const {
shipmentIds,
'name.en_US': name_en_US,
'name.fi_FI': name_fi_FI
} = device;
And then you could access your variable with name_en_US.
Here we are having two JSON called 1.contacts and 2.workers contacts json is having id called serviceId is nothing but id of workers. when i try to display contacts i want to display workers relevant to that contacts. Here is the stackblits DEMO
Here i have updated stackblitz using sample your data as Array.
https://stackblitz.com/edit/angular-movie-read-load-json-sample-eg-ujzzx1
Code:-
let finalResult:any[]=[];
for(let contact of this.contacts){
if(contact.serviceId){
finalResult.push(this.workers.filter(o=>o.id == contact.serviceId));
}
}
console.log("finalResult",finalResult);
You can gather the IDs from the contacts IDs in a map by using map then reduce. After that you iterate over your workers and check in the previously generated map if their serviceId is one of the map's keys.
It looks like this
const contacts = [{
"name": "Jhon Doe",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Peter Parker",
"gender": "Male",
"serviceId": "e39f9302-77b3-4c52-a858-adb67651ce86",
},
{
"name": "Mark Wood",
"gender": "Male",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
},
{
"name": "Mary Jane",
"gender": "Female",
"serviceId": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
}
];
const workers = [
{
"id": "e39f9302-77b3-4c52-a858-adb67651ce86",
"name": "Alfy Odhams"
},
{
"id": "38688c41-8fda-41d7-b0f5-c37dce3f5374",
"name": "Allsun Suttle"
},
{
"id": "ed780d15-428b-4bcd-8a91-bacae8b0b72e",
"name": "Alvinia Ettritch"
},
{
"id": "40665c50-ff74-4e81-b968-e127bdf1fe28",
"name": "Ambrosi Lindenstrauss"
}
];
const contactsIDs = contacts.map(c => c.serviceId).reduce((acc, curr) => {
acc[curr] = true;
return acc;
}, {});
const filteredWorkers = workers.filter(w => w.id in contactsIDs);
console.log(filteredWorkers);
when I did
loadPeople(){
this.myService.load().then(data => {
this.people = data;
alert(this.people);
});
}
it alerts json as :
{
"status": "true",
"statusCode": 200,
"response": [{
"user_id": "92",
"firstname": "joy",
"lastname": "Panchal",
"email": "joy#gmail.com",
"password": "7Y7+K0vZIVWPDUQH++Iu+/+tMZ",
"user_type_id": "1"
}, {
"user_id": "89",
"firstname": "mark",
"lastname": "haris",
"email": "mark#gmail.com",
"password": "4JICqnTkR8ysTI+nQQ+rpfAf7e",
"user_type_id": "1"
}]
}
now i am trying to access "response" by
loadPeople(){
this.myService.load().then(data => {
this.people = data.response;
alert(this.people);
});
}
but it alerts as "undefined" .
can anyone tell where i am missing ??
you can access like this. please try.
`loadPeople(){
this.myService.load().then(data => {
this.people = JSON.parse(data.response);
alert(this.people);
});
}`
you need parse JSON first:
this.myService.load().then(data => {
let res = JSON.parse(data);
this.people = res.response;
alert(this.people);
});
}
I've been learning a lot about denormalised data over the past few months, but I wanted to know if the following is possible in a flattened architecture world. I know how to handle two-way relationships in Firebase, but what about a three-way relationship. Let me explain...
I have 5 items in my database, services, providers, serviceAtProvider, reviews and users. I want to be able to add providers to services and vice versa.
I'd also like there to be a specific page for a provider inside a service, and for there to be reviews linked to the provider at that specific service. The page url might look like this (site.com/serviceId/providerId). The rating is unique to that providerId inside of that serviceId – you can't rate serviceIds or providerIds separately.
I'm not sure how to go about creating such a complex relationship. How would I join the serviceId and providerId in that serviceAtProvider item?
This is what I've got so far:
"services": {
"service1": {
"name": "Hernia Repair",
"providers": {
"provider1": true,
"provider2": true
}
}
},
"providers": {
"provider1": { "name": "The Whittington Hospital" },
"provider2": { "name": "Homerton Hospital" }
},
"serviceAtProvider": {
"service1AtProvider1": { "rating": 4 },
"service1AtProvider2": { "rating": 3 }
},
"reviews": {
"service1AtProvider1": {
"review1": {
"body": "A review from user 1",
"user": "user1"
}
},
"service1AtProvider2": {
"review1": {
"body": "A review from user 2",
"user": "user2"
}
}
},
"users": {
"user1": { "name": "Ben Thomas" },
"user2": { "name": "Beatrix Potter" }
}
I don't know how to create that serviceAtProviderjoin, or how would I go about accessing the service1.name, provider1.name, service1AtProvider1.rating, reviews.service1AtProvider1 on one page. Can anyone explain how to do this?
Also, are there any best practices I should follow?
Any help is appreciated. Thanks in advance!
UPDATE
{
"availableServices": {
"service1": { "name": "Hernia Repair" },
"service2": { "name": "Chemotherapy" }
},
"services": {
"provider": {
"name": "The Whittington Hospital",
"service": {
"service1": {
"rating": 4,
"reviewId1": true
},
"service2": {
"rating": 3,
"reviewId2": true
},
}
}
},
"reviews": {
"reviewId1": {
"review1": {
"rating": 4,
"body": "A review from user 1",
"user": "user1"
}
}
},
"users": {
"user1": { "name": "Raphael Essoo-Snowdon" },
"user2": { "name": "Sharlyne Slassi" }
}
}
I would start by making the data structure a bit simpler and more direct. It's hard to determine the correct data structure for your needs without a detailed use case. I'll do my best to make some generic assumptions here. You'll have to adapt as necessary.
{
"service": {
"service1": { "name": "Foo Service" },
...
},
"provider": {
"provider1": { name: "Foo Place" },
...
},
"ratings": {
"service1": { // service id
"provider1": { // provider id
"average_rating": 4
},
...
},
...
},
"reviews": {
"service1": { // service id
"provider1": { // provider id
"user": "user1",
"rating": 4
},
...
},
...
},
"user": {
"user1": { "name": "Foo Bar" },
...
}
}
Now, to look up the providers who offer a given service, and grab their reviews, I would do the following:
var ref = new Firebase(...);
ref.child('ratings/service1').on('child_added', function(reviewSnap) {
console.log(
'Provider ' + reviewSnap.key(),
'Average rating ' + reviewSnap.val().average_rating
);
});
Joining in the names of the services and providers could be done in several ways. Here's a manual technique:
var ref = new Firebase(...);
ref.child('ratings/service1').on('child_added', accumulateReview);
function accumulateReview(reviewSnap) {
var reviewData = reviewSnap.val();
var reviewid = reviewSnap.key();
fetchService(reviewSnap.parent().key(), function(serviceSnap) {
loadRec('provider', reviewSnap.key(), function(providerSnap) {
console.log('Provider: ', providerSnap.key(), providerSnap.val().name);
console.log('Service: ', serviceSnap.key(), serviceSnap.val().name);
console.log('Average rating: ', reviewData.average_rating);
});
});
}
var serviceCache = {};
function fetchService(serviceid, done) {
// demonstrates creating a local cache for things that will be
// looked up frequently
if( !serviceCache.hasOwnProperty(serviceid) ) {
cacheService(serviceid, done);
}
else {
done(serviceCache[serviceid]);
}
}
function cacheService(serviceid, done) {
loadRec('service', function(ss) {
serviceCache[serviceid] = ss;
fetchService(serviceid, done);
});
}
function loadRec(type, key, done) {
ref.child(type).child(key).once('value', done);
}
I could also automate some of this process with Firebase.util's NormalizedCollection:
var ref = new Firebase(...);
var nc = Firebase.util.NormalizedCollection(
[ref.child('reviews/service1'), 'review'],
ref.child('provider'),
ref.child('user')
)
.select('review.rating', {key: 'provider.name', alias: 'providerName'}, {key: 'user.name', alias: 'userName'})
.ref();
nc.on('child_added', function(snap) {
var data = snap.val();
console.log('Provider', data.providerName);
console.log('User', data.userName);
console.log('Rating', data.rating);
});
Note that nothing here is set in stone. This is how I would approach it. There are probably dozens of structures at least as good or better.
I am using following NodeJs code to get the JsonObject:
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index];
}
res.send(resp);
});
Getting output :
{
"emp1": {
"cas": {
"0": 637861888,
"1": 967242753
},
"flags": 0,
"value": {
"eid": "10",
"ename": "ameen",
"gender": "male",
"designation": "manager",
"country": "Singapur",
"reportee": "Suresh",
"salary": 50000,
"picture": "ameen.jpg"
}
},
"emp2": {
"cas": {
"0": 721747968,
"1": 430939000
},
"flags": 0,
"value": {
"eid": "2",
"ename": "shanmugapriya",
"gender": "female",
"designation": "programmer",
"country": "England",
"reportee": "shruti",
"salary": 14250,
"picture": "priya.jpg"
}
}
}
What I want to do is, I want to display only value key. Can anybody help me how to do this.
Thanks in advance.
Do you mean you want to display only value and key? If so the code below will put only value into the result
cdb.getMulti(['emp1','emp2'],null, function(err, rows) {
var resp = {};
for(index in rows){
resp[index] = rows[index].value;
}
res.send(resp);
});
The result response will be
{
"emp1":{
"eid":"10",
"ename":"ameen",
"gender":"male",
"designation":"manager",
"country":"Singapur",
"reportee":"Suresh",
"salary":50000,
"picture":"ameen.jpg"
},
"emp2":{
"eid":"2",
"ename":"shanmugapriya",
"gender":"female",
"designation":"programmer",
"country":"England",
"reportee":"shruti",
"salary":14250,
"picture":"priya.jpg"
}
}
UPDATE: Your question was really ambiguous. I think you would need to use Couchbase Views here. Docs http://docs.couchbase.com/couchbase-sdk-node-1.2/#querying-a-view. Assuming that you will build the view _design/employees/_view/all with the following map function:
function(doc, meta) {
emit(meta.id, doc);
}
Your node.js code will look like this
var view = bucket.view('employees', 'all');
view.query(function(err, results) {
res.send(results);
});