var footballerIdToPassive = "qqqqq";
var footballerlevelToPassive = ["3052002","3052003"];
db.goals.find({ "footballer": footballerIdToPassive, "footballerlevel": { $in: [footballerlevelToPassive]}}))
for that it brings nothing but in goals db shell, when i run count of this, count is 1
{ "footballer": "qqqqq", "footballerlevel": "3052002" }
also for
var footballerlevelToPassive = "3052002";
this, it works. but i cant do for multiple. HOw can i do this work?
i need to use each , i need to update each one
footballerlevelToPassive is already an array, there's no need to wrap it in another array again in your query, just reference it directly with $in as
var footballerIdToPassive = "qqqqq";
var footballerlevelToPassive = ["3052002","3052003"];
db.goals.find({
"footballer": footballerIdToPassive,
"footballerlevel": { "$in": footballerlevelToPassive }
})
which is equivalent to the query
db.goals.find({
"footballer": footballerIdToPassive,
"$or": [
{ "footballerlevel": "3052002" },
{ "footballerlevel": "3052003" }
]
})
Quick demo
Related
I want to update automatically the value of comments_list with the values in the comments JSON object
const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]})
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"})
The final output should look like this
{"tweet_id":1,"created_at":"2022-06-28","comments_list":[{"commenter_id": 2"commenter_first_name":"tito","commenter_username":"tito_lulu"}]}
I'd work with those strings in an object form, otherwise string-manipulation could be slow in some cases.
This is by no means the fastest solution but perhaps the idea behind it can be helpful.
const tweet = [{
"tweet_id": 1,
"created_at": "2022-06-28",
"comments_list": []
}]; // There could be many tweet objects so wrap it in an array
const comments = [{
"tweet_id": 1,
"commenter_id": 2,
"commenter_first_name": "tito",
"commenter_username": "tito_lulu"
},
{
"tweet_id": 1,
"commenter_id": 5,
"commenter_first_name": "me-too",
"commenter_username": "me294"
}
]; // Same here, could be many comments right?
let UpdatedTweets = [];
// There are faster ways to do this, but for your question
tweet.forEach((tweet, tweetIndex) => {
// Loop each tweet
let post = tweet;
comments.forEach((comment, commentIndex) => {
if (comment.tweet_id == tweet.tweet_id) {
// we have a match lets combine them
tweet.comments_list.push({
commenter_id: comment.comment_id,
commenter_first_name: comment.commenter_first_name,
commenter_username: comment.commenter_username
});
}
});
UpdatedTweets.push(post);
});
console.log(JSON.stringify(UpdatedTweets));
The general idea is:
Parse the JSON into JS objects
Update the target object with the complementary information
Stringify the target object into JSON (only if you need to, eg. send the data to some other machine)
In your case:
const tweet = JSON.stringify({"tweet_id":1,"created_at":"2022-06-28","comments_list":[]});
const comments = JSON.stringify({"tweet_id":1,"commenter_id": 2,
"commenter_first_name":"tito","commenter_username":"tito_lulu"});
let o_tweet = JSON.parse(tweet)
, o_comments = JSON.parse(comments)
;
if (Array.isArray(comments)) { // Test whether that is a single or multiple comments
comments.forEach( c => { o_tweet.comments_list.push(c); });
} else {
o_tweet.comments_list.push(o_comments);
}
console.log(o_tweet);
// Only if needed:
// let newtweet = JSON.stringify(o_tweet)
I have the following problem:
I want to read out my table names from a SQL database and then make a comparison as to whether it already exists. I know there is the formula IF EXISTS ... but IF doesn't work .. So here's my previous variant:
First i extracted everything before the filename.csv (C:\Users\Frederic\Desktop\Drag&Drop...) and then the ".csv". Do not be surprised why 51;) The filename is so long
var filename = filePath.slice(51);
var richtigername = filename.replace(".csv","").toString();
console.log(richtigername)
here the result in the console:
for example: fxbewertung
As a second step I let me show the file names:
connection.query('Show tables from datein', function(err, datein) {
let string = JSON.stringify(datein);
let json = JSON.parse(string);
console.log(json)
here the result in the console:
[ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
Furthermore, I extracted the values (name of the SQL tables):
for (var k = 0; k < json.length; k++) {
var werte = Object.values(json[k])
console.log(werte)
};
here the result in the console:
[ 'fxbewertung' ]
[ 'kontoauszug' ]
[ 'lsreport' ]
Now I don't know how i can take the comparison that for example for the file fxbewertung exist a database ('fxbewertung').
My consideration is to somehow browse the individual arrays .. or merge and then browse. At the end should come out true or false
P.S .: it may well be complicated yet but I'm not a real programmer or something;)
Best regards
Frederic
You can use some() method to check if a table exists for that filename.
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
Live Example:
var tables = [{
Tables_in_datein: 'fxbewertung'
},
{
Tables_in_datein: 'kontoauszug'
},
{
Tables_in_datein: 'lsreport'
}
];
var filename = 'fxbewertung';
var tableExists = tables.some(item => item['Tables_in_datein'] === filename);
if (!tableExists) {
// Table not found for filename.
} else {
// Table found. Do something.
}
Assuming you finished executing your query and stored the data as following:
const queryResult = [ { Tables_in_datein: 'fxbewertung' },
{ Tables_in_datein: 'kontoauszug' },
{ Tables_in_datein: 'lsreport' } ]
You'll then need to map this array to extract the values and store them in a single array like so:
const values = queryResult.map(e=>e[Object.keys(e)[0]]) // ["fxbewertung", "kontoauszug", "lsreport"]
Since you're looking for a true/false result by giving a file name, you'll need to use indexOf to achieve that.
const valueExists = filename => values.indexOf(filename) !== -1
After that execute valueExists with the file name you're looking for:
valueExists("kontoauszug"); // true
valueExists("potato"); // false
Hope this helps!
An efficient solution could be to use Array.prototype.find(). Where it would return from the moment it finds a truthy value and would not iterate till the end (unless the match exists at the end).
Demo Code:
const tablesArr = [
{
Tables_in_datein: "fxbewertung"
},
{
Tables_in_datein: "kontoauszug"
},
{
Tables_in_datein: "lsreport"
}
];
const tabletoFind = "fxbewertung";
const tableFound = tablesArr.find(item => item["Tables_in_datein"] === tabletoFind) ? true: false;
console.log(tableFound);
if(tableFound){
//*yes table found*/
}else{
///*nope table not found*/
}
I have a document like this in mongo collection :
{
"_id" :"sdsfsfd323323323ssd",
"data" : {
"('State', 'Get-Alert', 'BLIST_1', 'MessageData')" : [
"$B_Add-Server",
"$B_Pool1_0_Server"
],
"('State', \"Get-Server -Server 'uds412'\"):[
"$B_Add-Server",
"$B_Pool2_0_Server"
]
}
and I need to update "uds412" to "newValue".
Someone please help , how to find and replace it ?
Thanks
You can convert you valid JSON object into string and replace string to new value and again parse it into valid JSON object.
obj={ ...YOUR JSON OBJECT... }
newobj = JSON.parse(JSON.stringify(obj).replace('uds412','newValue'))
Finally , i solve it like this,
problem was , i need to find substring from key and update that key.
// first query the document
db.server_col.find().forEach(function (docs) {
var tempData = {};
var tempDataAr = [];
for (var key in docs["data"]) {
var find = /'uds412'/;
if (key.match(find)) {
tempDataAr = docs["data"][key]
key = key.replace('uds412', 'newValue');
tempData[key] = tempDataAr;
} else {
tempData[key] = docs["data"][key];
}
}
print(tempData);
// then you can update it
db.server_col.update({ "_id" : ObjectId("sdfsfdafs")}, { $set: { 'data':tempData } }, { multi: true })
});
I have situation like this
const links = {
ALLOWED1: [ 'some_path1' ],
ALLOWED2: [ 'some_path2' ]
}
However I want to also allow paths from previous array on ALLOWED2, I've tried
const links = {
ALLOWED1: [ 'some_path1' ],
ALLOWED2: [ ...links['ALLOWED1'], 'some_path2' ]
}
But this is not valid as links will not defined yet. Of course I can populate it manually, but would rather find a more elegant solution.
You could do it with three lines instead
const links = {};
links.ALLOWED1 = [ 'some_path1' ];
links.ALLOWED2 = [ ...links['ALLOWED1'], 'some_path2' ];
console.log(links.ALLOWED2);
Remember, const only keeps the reference to the object constant, not the object's contents. For that you would need Object.defineProperty
If the contents of allowed1 and allowed2 ever change I might consider using a function to get them both. Like: links.all = () => [...links.ALLOWED1, ...links.ALLOWED2]. To me, that would read clearer in the code, unless it's really clear that allowed2 will always be a superset of allowed1.
If you're not going to change ALLOWED2, you can convert it to a getter:
const links = {
ALLOWED1: [ 'some_path1' ],
get ALLOWED2() { return [ ...this['ALLOWED1'], 'some_path2' ] }
}
console.log(links.ALLOWED2);
An alternative, just because there are many ways to do this and it's mostly a matter of style :)
const links = (() => {
const ALLOWED1 = ["some_path1"],
ALLOWED2 = [...ALLOWED1, "some_path2"];
return { ALLOWED1, ALLOWED2 };
})();
console.log(links);
var usersRows = [];
connection.query('SELECT * from users', function(err, rows, fields) {
if (!err) {
rows.forEach(function(row) {
usersRows.push(row);
});
console.log(usersRows);
}
else {
console.log('Error while performing Query.' + err);
}
});
It returned to me:
var usersRows = [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ];
I need to parse this and remove rowdatapacket; I need result like this:
userRows = { id: 1, name: 'my name is', number: '+999999\r\n' };
If you need to get rid of RowDataPacket's array and save it in yours you can also use this:
usersRows = JSON.parse(JSON.stringify(results));
Have you tried
userRows = RowDataPacket;
You might want to try JSON.stringify(rows)
Was unable to understand and implement the accepted the answer.
Hence, tried the long way out according the results I was getting.
Am using "mysql": "2.13.0" and saw that the this library returned array of array out of which:
Index 0 had array of RowDataPackets
Index 1 had other mysql related information.
Please find the code below:
var userDataList = [];
//Get only the rowdatapackets array which is at position 0
var usersRows = data[0];
//Loop around the data and parse as required
for (var i = 0; i < usersRows.length; i++) {
var userData = {};
//Parse the data if required else just
userData.name = userRows.firstName + userRows.lastName;
userDataList.push(userData);
}
If no parsing is required and you just want the data as is, you could use the solution like mentioned in link How do I loop through or enumerate a JavaScript object?
Have not tried it but could be tweaked and worked out.
There should be simpler way to do it but as a novice I found the above way server the purpose. Do comment in case of better solution.
RowDataPacket is the class name of the object that contains the fields.
The console.log() result [ [ RowDataPacket { id: 1, name: 'sall brwon', number: '+99999999\r\n' } ] ] should be read as "an array of one item, containing and array of one item, containing an object of class RowDataPacket with fields id, name, and number"