I have an array with objects. I want to import these into a sqlite3 database. I
do this with a forEach loop. It works well. But I wonder why the objects are not
imported in the order I put them into the database.
This is what I do
const comments = [
{post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
]
comments.forEach(c => {
sql = `INSERT INTO comments(post_id, comment, comment_author) VALUES (?,?,?)`
db.run(sql, [c.post_id, c.comment, c.comment_author], (err) => {
if (err) { console.log(err.message)};
});
});
If I now execute a select, I get the following pure order (take a look to post_id):
[
{id: 1, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"},
{id: 2, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"}
]
Question Why is this happening? And what can I do to change the behavior.
Expected result:
[
{id: 1, post_id: 1, comment: "lorem ipsum comment 1", comment_author: "user 1"},
{id: 2, post_id: 2, comment: "lorem ipsum comment 2", comment_author: "user 1"}
]
Note I Guess it has something to do with the async of javascript.
You are right with your guess: I Guess it has something to do with the async of javascript.!
let placeholders = comments.map((c) => '(?)').join(',');
let sql = 'INSERT INTO comments(post_id, comment, comment_author) VALUES ' + placeholders;
// output the INSERT statement
console.log(sql);
db.run(sql, [comments], (err, results, fields) => {
if (err) {
return console.error(err.message);
}
// get inserted rows
console.log('Row inserted:' + results.affectedRows);
});
// close the database connection
db.close();
Related
So I have this dataBase that is gonna be used in the app.get function below. The goal is to make the app.get send the first item in the array dataBase (which is the array "posts") as the value for the object's atribute "posts:". In case I don't set any names for the array and call it in the app.get as "posts: dataBase[0]", it works - the forEach() can read it; otherwise, it seems it's not called as an array since the .forEach() can't be used.
const dataBase =
[
posts = [
{
title: "Post 1",
text: "Lorem ipsum",
stars: 2
},
{
title: "Post 2",
text: "Lorem ipsum"
},
{
title: "Post 3",
text: "Lorem ipsum",
stars: 5
}
],
ads = {}
]
app.get("/posts", (req, res)=>{
res.render("posts",
{
title: "Basic Project: Posts",
posts: dataBase[dataBase.indexOf("posts")]
}
)
})
IN THE .ejs FILE:
<article class="content">
<h1>POSTS:</h1>
<% posts.forEach(item=>{ %> <!-- ERROR: forEach is not a function -->
<div>
<% if (item.stars){ %>
<% for(let i = 0; i < item.stars; i++){ %>
<img src="images/star.pgn">
<% } %>
<% } %>
<h3><%= item.title %></h3>
<p><%= item.text %></p>
<br>
</div>
<% }) %>
</article>
You're mixing the concepts of arrays and objects. In JS they are not the same thing.
Your database should probably be:
const dataBase = {
posts: [
{
title: "Post 1",
text: "Lorem ipsum",
stars: 2
},
{
title: "Post 2",
text: "Lorem ipsum"
},
{
title: "Post 3",
text: "Lorem ipsum",
stars: 5
}
],
ads: {}
}
Then you can access posts simply with dataBase.posts.
Here is some more details about arrays vs objects: https://medium.com/#zac_heisey/objects-vs-arrays-42601ff79421.
I'm building my first Node.js API.
In the endpoint '/posts' I have a return like this:
[
{
"POST_ID": 1,
"POST_TITLE": "Post N.1",
"POST_DESCRIPTION": "Description for Post N.1",
"POST_PHOTO_URL": "Url for image 1 of post 1"
},
{
"POST_ID": 1,
"POST_TITLE": "Post N.1",
"POST_DESCRIPTION": "Description for Post N.1",
"POST_PHOTO_URL": "Url for image 2 of post 1"
},
{
"POST_ID": 2,
"POST_TITLE": "Post N.2",
"POST_DESCRIPTION": "Description for Post N.2",
"POST_PHOTO_URL": "Url for image 1 of post 2"
},
{
"POST_ID": 2,
"POST_TITLE": "Post N.2",
"POST_DESCRIPTION": "Description for Post N.2",
"POST_PHOTO_URL": "Url for image 2 of post 2"
}
]
How can I merge the objects that have the same POST_ID, and make the POST_PHOTO_URL an array that contains all the URLS for the same post?
I want something like this:
responseObj = {
postId: 0,
postTitle: "Post N.1",
postDescription: "Description for Post N.1",
postImages: ['first_url', 'second_url'],
};
My SQL Query is: SELECT P.POST_ID, P.POST_TITLE, P.POST_DESCRIPTION, PI.POST_PHOTO_URL FROM POST P INNER JOIN POST_ITEMS AS PI ON P.POST_ID = PI.POST_ID
SQL SERVER.
I have no SQL SERVER to test this, but your desired output could probably be created with the following query.
SELECT P.POST_ID AS postId, P.POST_TITLE AS postTitle, P.POST_DESCRIPTION AS postDescription, oa.postImages
FROM POST P
OUTER APPLY(
SELECT PI.POST_PHOTO_URL AS postImages
FROM POST_ITEMS PI
WHERE PI.POST_ID = P.POST_ID
FOR JSON PATH
) oa
This should return an JSON representation of the desired POST_PHOTO_URLs.
You have to parse these to get your array.
result.forEach(r => {
r.postImages = JSON.parse(r.postImages);
})
The filter on UI allows a user to search using the IN criterion. The search string will then become the property of the condition Object.
The search string will look like "1234,5436,8765" and then the condition Object will be like ```
condition: {
field: "Id",
operator: "in",
value: "1234,5436,8765"
}
Now as this is going to be IN filter, so whar criterion should I use so as to make the value search like IN criterion from the results Array.
e.g. for a like filter, I will set my value property like this %1234% so as to search this in the results Array.
Your question isn't clear so try to edit it to make it clearer.
I made a huge assumption here in my answer (as it is not clear from the question):
You could do it with a switch statement and then your various filter methods for each case.
You could do it more robustly, but until the question is clearer, it doesn't make much sense to build this solution out.
const myArrOfObs = [
{Id: 1234, title: "some title 1", other: "some other val 1"},
{Id: 2468, title: "some title 2", other: "some other val 2"},
{Id: 8240, title: "some title 3", other: "some other val 3"},
{Id: 9371, title: "some title 4", other: "some other val 4"},
{Id: 5436, title: "some title 5", other: "some other val 5"},
{Id: 8365, title: "some title 6", other: "some other val 6"},
{Id: 8765, title: "some title 7", other: "some other val 7"},
{Id: 3946, title: "some title 8", other: "some other val 8"}
];
const condition = {
field: "Id",
operator: "in",
value: "1234,5436,8765"
};
function filterArr(arr, cond) {
switch (cond.operator){
case "in":
const valueArr = cond.value.split(',');
return arr.filter(item => valueArr.includes(item[cond.field].toString()));
//case "like":
//return arr.filter( ... );
default:
return null;
}
}
const myFilteredArr = filterArr(myArrOfObs, condition);
console.log(myFilteredArr);
Sorry for the noob question but I am just getting started with Angular. I have this array declared in services.js:
var articles = [{
id: 1,
title: 'Article 1 Title',
intro: 'Article 1 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 1 Text',
url: 'http://www.domain.com'
}, {
id: 2,
title: 'Article 2 Title',
intro: 'Article 2 Intro',
image: 'photo.jpg',
published: '27/10/2016',
text: 'Article 2 Text',
url: 'http://www.domain.com'
}];
Now that everything works fine in my Angular App I want to read this array from a JSON file that can be found, for example, at www.domain.com/articles.json and it looks like this:
{
"articles": [
{
"id": 1,
"title": "Article 1",
"intro": "Article 1 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 1 Text",
"url": "http://www.domain.com/article-1"
},
{
"id": 2,
"title": "Article 2",
"intro": "Article 2 Intro",
"image": "image.png",
"published": "27/10/2016",
"text": "Article 2 Text",
"url": "http://www.domain.com/article-2"
}
]
}
How can I make this change?
To get the data of the file in your Angular app, you'll have to get the file's contents through an HTTP request. The easiest way to do this is by using the $http service.
Example (with relative url):
$http.get('/articles.json').then(function (response) {
var articles = response.data.articles;
// Do something with articles...
});
The callback function you're passing to the then method will be called when the HTTP request was successful. Note that your data will only be available in this callback function. Also don't forget to include a dependency to the $http service in your controller. ;)
I got a simple json api and want to display some of objects fields with react.
The api has the following structure:
{"data" : [
0: Object
id: "1"
type: "Item"
attributes: Object
title: "lorem impsum"
body: "lorem ipsum"
1: Object
id: "2"
....
]}
And I'm trying to display attributes items(title, body)
The problem is that
this works fine and displays id
{items.map(item =>
<div>{item.id}</div>
)}
BUT
If I try to use {item.attributes.title} I receive
TypeError: Cannot read property 'title' of undefined
So item.attributes is undefined.
What's wrong here?
this is the most common error that occurs because you never know what object you are going to get from server, so it is always good way to check before accessing the data, so you can try
{item.attributes && item.attributes.title ? item.attributes.title : 'print something for missing title' }
//item.attributes && item.attributes.title means if both the values are present in Object
This should help you. I couldn't find an error in your program. So, I've created a working example to solve this.
const data = {
"data": [{
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}, {
id: "1",
type: "Item",
attributes: {
title: "lorem impsum",
body: "lorem ipsum",
}
}]
}
class Sample extends React.Component{
render() {
return <div>
{
data.data.map((el) => {
return <div>
<h1>{el.id}</h1>
<div>{el.attributes.title}</div>
<div>{el.attributes.body}</div>
</div>
})
}
</div>
}
}
ReactDOM.render(<Sample/>, document.getElementById('app'))
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/react/15.1.0/react-dom.min.js"></script>
<div id="app"></div>