Error querying by string in nodejs api rest - javascript

I'm actually creating an app for my neighborhood little business, y have this db schema using Postgresql:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_schema_db_dykxnt.png
my use cases are:
1 user can create 1 experience.
1 user can create a business local only if its going to leave an experience from it.
1 experience can have several images.
( I haven't a relationship between business_locals and users because doesn't matter for who creates the business).
I haven't had problems untill now, I'm trying to get the business with it's name, lat and lng; the average score given by users, 1 image from the last experience where the name like = "somestring"
this are my models:
Business Model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_businessmd_rwnsnu.png
Images model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_imgaesmd_m4hkzv.png
experiencies model: https://res.cloudinary.com/dthhugesg/image/upload/v1569939688/nodejserror/lugarlov_experienciesmd_f7jtxt.png
y try this code:
export async function getBusinessByQueryString(req, res) {
let query = req.params.query;
const businessesResult = await Business.findAll({
where: Sequelize.where(
Sequelize.fn("LOWER", Sequelize.col("name")),
{
[Op.like]: `%${query}%`
}
),
attributes: ['name', sequelize.fn('COUNT', sequelize.col('experiencies.id'))],
include: [
{ model: Experiencies, attributes: [] }
],
group: ["business_locals.id"]
}).catch(err => {
return res.status(500).json({
ok: false,
messagge: "Error al consultar el comercio",
err
});
});
console.log(businessesResult);
// let businessIdArrays = businessesResult.map((obj) => obj.id);
// console.log(businessIdArrays);
return res.json({
ok: true,
message: businessesResult
});
}
but I'm having this error:
https://res.cloudinary.com/dthhugesg/image/upload/v1569939691/nodejserror/error_x0tsiq.png
I'm expecting this:
[
{
"id": 2,
"name": "Business local example 1",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/tech"
},
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 2,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 3,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
},
{
"id": 3,
"name": "Business local example 2",
"lat": 6.24523,
"lng": -75.4543,
"average_score": 4,
"experiences": [
{
"id": 1,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [
{
"url": "https://placeimg.com/640/490/animals"
}
],
"user": {
"id": 2,
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
},
{
"id": 4,
"comment": "was a good experience to be there, good food and cool service",
"score_given": 4,
"created_at": "2019-09-30 18:55:00",
"images": [],
"user": {
"name": "Esteban nuevo nombre",
"phone": "0000000+"
}
}
]
}
]
thank you very much, all of you i hope that someone can help me and tell me if i have any mistake

Related

how to join 3 tables in laravel using eloquent hasmanythrough or hasonethrough

this is my tables look like
departments
course
subjects
id
id
id
head
department_id
course_id
course_name
subject_code
in my models this is how I do it but seems not working and I don't know why:
public function departments()
{
return $this->hasOneThrough(
subjectlist::class,
department::class,
'id',
'course_id',
'id',
'id'
);
}
The output when I try to use hasOneThrough:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith#gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
}
}
I wan't the output should be like this please help me how to do it:
{
"id": 1,
"department_name": "Business",
"head": "John smith",
"email": "smith#gmail.com",
"contact_number": "09300282103",
"created_at": null,
"updated_at": null,
"subject_list": {
"id": 1,
"course_id": 1,
"subject_code": "Math1",
"description": "math test",
"year_type": 1,
"price": "200.00",
"units": "5.00",
"created_at": null,
"updated_at": null,
"laravel_through_key": 1
},
"department": {
"id": 1,
"department_name": "ComputerScience"
}
}
Relationship between your tables are like
Subject as a Course
Course has a Department
and Subject has a department through course
Relation For Your Subject Model
public function Course() {
return $this->belongsTo(Course::class);
}
public function Department() {
return $this->hasOneThrough(Department::class, Course::class)
}
Relation For Your Course Model
public function Subject() {
return $this->hasMany(Subject::class);
}
public function Department() {
return $this->belongsTo(Department::class);
}
Relation For Your Department Model
public function Course() {
return $this->hasMany(Course::class);
}
For farther info refer to laravel eloquent relationships documentation
https://laravel.com/docs/8.x/eloquent-relationships#has-one-through

mongoDB - How do master-detail structure grouped detail collection specific fields summary

In a mongodb database with a master-detail structure, how do I ensure that the data in the detail table is grouped according to the status area while querying the master table. For example ...
Master, Row, Job, Fields, [Detail Status Grouped Count / Summary Object]
Edited:
sms_jobs collection example data is :
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z")
}
sms_job_details collection example data is :
// 1
{
"_id": NumberInt("221462"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "waiting", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 2
{
"_id": NumberInt("221463"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "failed", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
// 3
{
"_id": NumberInt("221464"),
"sms_job_id": NumberInt("1"),
"gsm": "",
"schedule_at": ISODate("2020-08-15T19:41:44.827Z"),
"raw_message": "{name} {surname} {id_number} {form_link} {reject_link}",
"message": "",
"status": "success", // I want this statuses grouped count my master table rows in line object
"expire_at": "2020-08-18T17:40:44.967Z",
"updated_at": ISODate("2020-08-15T18:45:53.727Z"),
"created_at": ISODate("2020-08-15T18:45:53.727Z")
}
I experimented for approximately 4-5 hours. I could get the closest result with the following query.
db.getCollection("sms_jobs").aggregate([{
$lookup: {
from: "sms_job_details",
localField: "_id",
foreignField: "sms_job_id",
as: "data"
}
}, {
$unwind: "$data"
}, {
$group: {
_id: {
id: "$_id",
status: "$data.status"
},
qty: {
$sum: 1
}
}
}, {
$project: {
_id: "$_id.id",
qty: 1,
status: "$_id.status"
}
}])
And get this result :
// 1
{
"qty": 22145,
"_id": NumberInt("4"),
"status": "success"
}
// 2
{
"qty": 1,
"_id": NumberInt("3"),
"status": "success"
}
// 3
{
"qty": 22142,
"_id": NumberInt("1"),
"status": "success"
}
// 4
{
"qty": 1,
"_id": NumberInt("1"),
"status": "failed"
}
// 5
{
"qty": 2,
"_id": NumberInt("1"),
"status": "waiting"
}
// 6
{
"qty": 1,
"_id": NumberInt("3"),
"status": "failed"
}
// 7
{
"qty": 3,
"_id": NumberInt("3"),
"status": "waiting"
}
What do I want ?
The query result I want is as follows.
// 1
{
"_id": NumberInt("1"),
"company": {
"id": NumberInt("1"),
"name": "",
"sms_gateway_id": NumberInt("1"),
"sms_gateway_parameters": {
"password": "",
"username": ""
},
"is_active": true
},
"source_type": "form",
"source": {
"id": NumberInt("2"),
"company_id": NumberInt("1"),
"title": "Import Data Demo",
"description": "<p>Üst Açıklama</p>",
"footer_description": "<p>Alt Açıklama</p>",
"thanks_message": "Katiliminiz icin tesekkur ederiz.",
"sms_message": "{company} KVKK Aydinlatma Metni ve Acik Riza Onayi icin Dogrulama Kodunuz : {code} ( {form_link} )",
"digest": null,
"ts_digest": null,
"is_active": true,
"is_locked": false
},
"description": "Import Data Demo",
"status": "waiting",
"job_count": NumberInt("22145"),
"updated_at": ISODate("2020-08-15T17:00:49.252Z"),
"created_at": ISODate("2020-08-15T16:59:10.899Z"),
// Added part...
"status_countes": {
"success": NumberInt("20"),
"failed": NumberInt("2"),
"waiting": NumberInt("11"),
"canceled": NumberInt("0"),
"total": NumberInt("33")
},
}
Thank you in advance for your help...

How to loop through nested JSON and append in HTML DOM

I am trying to loop through a JSON and append it to HTML in a nested way. What I am trying to do is add a Header tag for the title of the object and have tags for the titles of items. Some objects might not have the items as empty too. I am guessing a nested loop is required and I've tried implementing it. The JSON looks like:
[
{
"id": 1,
"title": "Hello",
"url": "http://localhost:8000/login/notes/1/",
"description": "Hello nice",
"created_at": "2019-08-10T06:02:55.468315Z",
"created_by": "Dude",
"items": [
{
"id": 1,
"url": "http://localhost:8000/login/items/1/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 2,
"url": "http://localhost:8000/login/items/2/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 4,
"url": "http://localhost:8000/login/items/4/",
"title": "postman5",
"note": "http://localhost:8000/login/notes/1/"
}
]
},
{
"id": 2,
"title": "abc",
"url": "http://localhost:8000/login/notes/2/",
"description": "asad",
"created_at": "2019-08-10T15:23:53.074848Z",
"created_by": "dude2",
"items": [
{
"id": 5,
"url": "http://localhost:8000/login/items/5/",
"title": "Parrot Toy",
"note": "http://localhost:8000/login/notes/2/"
}
]
}]
I've tried
fetch('http://localhost:8000/login/notes/?format=json',{mode: 'cors'})
.then(response => response.json())
.then(data => {
var output='';
var final='';
var semif='';
var darif='';
for (var i in data) {
output+=i+'<h2>'+data[i].title +'</h2>'
for(j in data[i].items){
final+='<li>'+data[i].items[j].title+'</li>'
}
semif=output+final
}
document.getElementById('test').innerHTML=darif
});
HTML
<p id="test">
</p>
What I want to achieve is:
<h1>Hello</h1>
<h5>baby's toy</h5>
<h5>baby's toy</h5>
<h5>postman5</h5>
<h1>abc</h1>
<h5>parrot's toy</h5>
I strongly advise against doing lengthy string concatenations. Strings are immutable objects and they can put unnecessary burden on your system.
In addition, using map and join is much more elegant and easier to read.
const data = [
{
"id": 1,
"title": "Hello",
"url": "http://localhost:8000/login/notes/1/",
"description": "Hello nice",
"created_at": "2019-08-10T06:02:55.468315Z",
"created_by": "Dude",
"items": [
{
"id": 1,
"url": "http://localhost:8000/login/items/1/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 2,
"url": "http://localhost:8000/login/items/2/",
"title": "baby's toy",
"note": "http://localhost:8000/login/notes/1/"
},
{
"id": 4,
"url": "http://localhost:8000/login/items/4/",
"title": "postman5",
"note": "http://localhost:8000/login/notes/1/"
}
]
},
{
"id": 2,
"title": "abc",
"url": "http://localhost:8000/login/notes/2/",
"description": "asad",
"created_at": "2019-08-10T15:23:53.074848Z",
"created_by": "dude2",
"items": [
{
"id": 5,
"url": "http://localhost:8000/login/items/5/",
"title": "Parrot Toy",
"note": "http://localhost:8000/login/notes/2/"
}
]
}]
const result = data.map(el => {
return `<h1>${el.title}</h1>` + el.items.map(el => `<h5>${el.title}</h5>`).join("")
}).join("")
console.log(result)
fetch('http://localhost:8000/login/notes/?format=json',{mode: 'cors'})
.then(response => response.json())
.then(data => {
var html = '';
data.forEach(listItem => {
const h1 = `<h1> ${listItem.title} </h1>`;
html+=h1;
listItem.items.forEach(item=> {
const h5 = `<h5> ${item.title} </h5>`;
html+=h5;
});
});
document.getElementById('test').innerHTML=html;
});
I think you may use it.

How to deep merge objects in react js

{"activities": [
{
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"foreign_id": "post.UsPost:253",
"id": "ed50e218-f3e8-11e8-8080-800132d8e9c0",
"object": {
"id": 253,
"comments": 0,
"likes": 0,
"files": [
{
"id": 112,
"file": "",
"content_type": "video/mp4",
"file_type": "video",
"created_at": "2018-11-29T15:10:38.524836Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/253/",
"target": "post.UsPost:253",
"foreign_id": "post.UsPost:253",
"actor": {
"id": 409,
"avatar": "",
"first_name": "Sakthi",
"last_name": "Vel",
"headline": null,
"is_online": false,
},
"text": "#Multiple video (.mp4) test. Far far away, behind the word mountains, far from the countries Vokalia and Consonantia, there live the blind texts. Separated they live in Bookmarksgrove right at the coast of the Semantics, a large language ocean.",
"skills": [
"VFX"
],
"created_at": "2018-11-29T15:10:37.426332Z",
"is_link": true,
"view_count": 0,
"created_by": 409
},
"origin": "user:409",
"target": "",
"time": "2018-11-29T15:10:37.426332",
"type": "post",
"verb": "posted"
}
{
"activities": [
{
"actor": {
"id": 64,
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"foreign_id": "post.UsPost:183",
"id": "447f6710-eb08-11e8-8080-8001369e78cd",
"object": {
"id": 183,
"comments": 1,
"likes": 1,
"files": [
{
"id": 87,
"content_type": "image/jpg",
"file_type": "image",
"created_at": "2018-11-18T08:02:18.759309Z"
}
],
"post_type": "post",
"is_bookmarked": false,
"is_liked": false,
"link": "/post/api/v1/183/",
"target": "post.UsPost:183",
"foreign_id": "post.UsPost:183",
"actor": {
"id": 64,
"first_name": "Uchenna",
"last_name": "",
"headline": "Learning is my Passion",
"is_online": false,
"username": "Uchenna1"
},
"text": "This is codigo",
"skills": [
"Javascript"
],
"created_at": "2018-11-18T08:02:17.626600Z",
"is_link": true,
"view_count": 10,
"created_by": 64
},
"origin": "user:64",
"target": "",
"time": "2018-11-18T08:02:17.626600",
"type": "post",
"verb": "posted"
}
],
"activity_count": 1,
"actor_count": 1,
"created_at": "2018-11-18T08:02:18.647108",
"group": "posted_2018-11-18",
"id": "451b1eab-eb08-11e8-8080-80007915e2b6.posted_2018-11-18",
"is_read": false,
"is_seen": true,
"updated_at": "2018-11-18T08:02:18.647108",
"verb": "posted"
}
I am facing issue in merging two object. Below is the snap of two object and result.
Here in the above image I wan to merge Old Data and new Data
but after merging getting wrong output i.e new updated data.
I am using command to do it.
let newData = { ...a , ...b }
console.log('new updated data: ',newData)
also I am performing this operation in redux action before dispatching.
Here {"activities": [....],....} is one object and I want to merge with the below one.
Can you clarify do your objects have a child that are objects or arrays and if you mean it's not merging those things or is it not merging anything at all?
for e.g:
let oldData = {
key: value,
key1: { childkey1: value1 }
}
if you have something like this and the problem is like I explained. It's because javascript doesn't do deep merge. it does a shallow merge.
Easiest option would be use a library like lodash that has a function for deep merge.

JSON new data push. How to save changes? With AngularJs

all. I'm new with Angular. I need to find out how to save my JSON changes after push.
app.controller('ReviewController', function(){
this.r = {};
this.addReview = function(product){
this.r.createdOn = Date.now();
product.reviews.push(this.r);
this.r = {};
};
});
also I have this thing, where I get JSON data. I don't know if it would be useful for you to know that
app.factory('events', function($http) {
return function(){
return $http.get('products.json');
};
});
app.controller("StoreController", function(events){
var store = this;
store.products = [];
events().success(function(data) {
store.products = data;
});
One more thing. My products.json file:
[
{
"title": "Rubinas",
"price": 199.99,
"description": "Labai kietas, davai pirkit.",
"images": {
"full": "images/gem2.gif",
"thumb": "images/gem2t.gif"
},
"reviews": [
{
"stars": 1,
"body": "Bullshit",
"author": "Hater",
"createdOn": 1397490980837
},
{
"stars": 3,
"body": "Simple stone!",
"author": "Dude",
"createdOn": 1397490980837
},
{
"stars": 5,
"body": "Amazing.",
"author": "Kate",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
},
{
"title": "Smaragdas",
"price": 499.99,
"description": "Oho, koks.",
"images": {
"full": "images/gem3.gif",
"thumb": "images/gem3t.gif"
},
"reviews": [
{
"stars": 5,
"body": "This is so amazing",
"author": "Steeler",
"createdOn": 1397490980837
},
{
"stars": 4,
"body": "Pretty cool!",
"author": "Jim",
"createdOn": 1397490980837
},
{
"stars": 2,
"body": "I don't like it very much.",
"author": "Kim",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
},
{
"title": "Deimantas",
"price": 9999.99,
"description": "Labai kietas, na bet rimtai.",
"images": {
"full": "images/gem4.gif",
"thumb": "images/gem4t.gif"
},
"reviews": [
{
"stars": 1,
"body": "Eww...",
"author": "Hater",
"createdOn": 1397490980837
},
{
"stars": 4,
"body": "Nice!",
"author": "Dude",
"createdOn": 1397490980837
},
{
"stars": 5,
"body": "So unbelievible.",
"author": "Matt",
"createdOn": 1397490980837
},
{
"stars": 2,
"body": "I don't like it.",
"author": "Steven",
"createdOn": 1397490980837
}
],
"canPurchase": true,
"soldOut": false
}
]
The are some ways to do this
First : You can create a button say called "save changes", and tell the user after finishing the process of adding new data with your so-called function addReview, Hit the save changes , and in the on-click of this button , you can create a $http.post request and send your new pushed array into your database (or your json file , whatever it is)
Second : You can do the same $http.post in your own function , addReview, without creating a button and listening for user to click on save changes button.
For example:
if you want to go for my second solution :
this.addReview = function(product){
this.r.createdOn = Date.now();
product.reviews.push(product);
this.r = {};
$http.post('yourServerFile',WhateverYouWantToSave)
.success(function(){
alert('Your Changes have been saved to database');
})
};
//Dont forget to inject $http into your controller
And its better to define a factory/servise for this kind of theories(pushing/adding/sending/deleting somethig from somewhere)

Categories

Resources