assigning a variable to a very big array make it undefined - javascript

I used some endpoint to get simple info for all crypto coins , this list is very big
2 clear examples to illustrate the problem
// example one
var arrWithSmallLength = [ {
name: 'Bitcoin',
symbol: 'btc',
id: 'bitcoin',
image: 'bitcoin_logo_url'
},.....];
// length of arrWithSmallLength is less than 1000
console.log(arrWithSmallLength); // it prints the array normally
// example two
var arrWithBigLength = [ {
name: 'Bitcoin',
symbol: 'btc',
id: 'bitcoin',
image: 'bitcoin_logo_url'
},.....];
// length of arrWithBigLength is more than than 8000
console.log(arrWithBigLength); // it prints undefined
The arrWithBigLength rendered in VS Code in more than 78500 lines
UPDATE
find the data payload in this link : https://drive.google.com/file/d/1FIbMoLbtzRm7LqMaPZnE3EAL26sj4VOo/view

In your json file, look for the value 'Staked yAxis'. After this entry you'll find
}
]
[
{
Here you repeat your data for a second time, causing a bad json definition. Remove the doubles after this line and your data works. Everything after line 39273 shouldn't be there (except for the closing }.

Related

get the uuid in an object array with Firebase

Hello I would like to know if there would be a method to recover the uuid when I push data in my table I put you in the screenshot below
the code
push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
The push function returns a Reference object, from which you can get the key with something like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`), {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
console.log(newRef.key);
If you want to use that key in the write operation, you can also separate the creating of the new ID from the writing of the data like this:
const newRef = push(ref(db, `/users/${auth.currentUser.uid}/user/sensors`));
console.log(newRef.key);
set(newRef, {
name: registerInformation.nameBox,
id: registerInformation.idBox,
categories: registerInformation.categories,
routine: registerInformation.routine,
});
In this snippet, the first line is a pure client-side operation that doesn't actually write anything to the database yet.

Filter inside the fetch with mongoDB query operators

how are you? I'm trying to move a filter inside the fetch I'm doing to bring my data from Builder.io and I'm struggling with one of them here. The title search works fine, but the second one don't. My objective is to filter between the entries to catch only the ones that match at least one of the annotationArray items.
The annotationArray can be, for example:
const annotationArray = ['Video', 'Image', 'GPS']
or just
const annotationArray = ['Video']
or whatever.
And the entries have an annotation field that consists in a string where I pass the annotations, like this:
const entries = [{title: 'First', annotation: 'Video, GPS'}, {title: 'Second', annotation: 'GPS'}, {title: 'Third', annotation: 'Video, Image'}]
So, for example, if the annotationArray is ['Video', 'GPS'], I want to fetch all of them. But if it's ['Video'], only the third and first, and so.
Currently I have this code
const sets = await builder.getAll('open-dataset', {
options: { noTargeting: true },
omit: 'data.blocks',
limit: 100,
query: {
data: {
title: { $regex: search, $options: 'i' },
annotation: { $regex: annotationArray && annotationArray.join(' '), $options: 'i' },
}
}
});
The result of annotationArray.join(' ') can be, for example, Video Image GPS or just Image. And annotation Video Image or whatever.
So I need to filter between the entries and fetch only the ones that contain at least one of the annotationArray strings.
My code is failing because currently it only fetches the ones that have all the annotationArray items, and not the ones that have at least one. I don't know how to do it with MondoDB query operators... previously, I had this code with javascript and it worked fine.
const filtered = entries.filter(item => annotationArray.some(data => item.annotation.includes(data)));
can somebody help me? thanks

How to read in this MongoDb field that contains dynamic children fields, in JavaScript?

Given the following MongoDB document structure (which I cannot change), I'm not sure how to read this in JavaScript?
so loginHistory is the main field name. It contains an Object type (okay???)
it can then contain multiple children fields (this above example has only ONE child), which are arrays. These field names are dynamic, but unique.
the 'array' content is a C# DateTimeOffset , I've been told.
So in the example above, Jane is the field and the value is an Array, but really it's a DateTime.Offset.
Here's another document I've found:
4x fields
So i don't know how to read this with node/JavaScript. Oh - and the field loginHistory might not exist on some documents, also :(
So given that existing document schema/structure, I need to somehow read in each loginHistory value and then create a new document (which i'll do other stuff with later).
This is some JavaScript code I tried, but doesn't work:
users.loginHistory.forEach(loginHistory => {
// do stuff, like create a new { id = users._id, name = "Jane", createdOn = "that date/time offset" }
}
Assuming we have an input set of docs like the screen shots e.g.:
var r = [
{
loginHistory: {
"Jane": [ 1648835363929, 0 ],
"Bob": [ 1648835363929, 0 ]
}
},
{
noLoginHistory: "nope"
},
{
loginHistory: {
"Dan": [ 1648835363929, 0 ],
"Dave": [ 1648835363929, 0 ],
"Jane": [ 1648835363929, 0 ]
}
}
];
then the following pipeline will create new, "converted" docs in a collection named foo2.
db.foo.aggregate([
// OK if loginHistory does not exist. X will be set to null
// and the $unwind will not produce anything:
{$project: {X: {$objectToArray: "$$ROOT.loginHistory"} }},
{$unwind: "$X"},
// Now we have individual docs of
// X: {k: name, v: the array}
// The OP wanted to make a new doc for each one. I don't know
// what function to apply to turn X.v[0] into a MongoDB datetime
// because I don't know what that big int (637807576034080256) is
// supposed to be so I used regular ms since epoch for the example
// instead. The OP will have to get more creative with division
// and such to turn 637807576034080256 into something "toDate-able"
// in MongoDB. You *could* store the big int as is but it is always
// good to try to turn a datetime into a real datetime in mongodb.
{$project: {
_id: false,
name: '$X.k',
createdOn: {$toDate: {$arrayElemAt:['$X.v',0]}}
}}
// Now we have docs like :
// {name: "Jane", createdOn: ISODate(...) }
// By calling $out to a new collection, a new _id will be assigned
// to each:
,{$out: "foo2"}
]);

mongoDB - Regex search against partial field values

I've a collection of countries with country calling code in the country object. How can I find a country using calling code with a mobile number?
const countries = [
{
name: 'UAE',
callingCode: 971
},
{
name: 'USA',
callingCode: 1
},
{
name: 'UK',
callingCode: 44
}
];
const number = '971524500000'; // Input
How can I find country for the given mobile using regex in mongoose javascript;
[https://en.wikipedia.org/wiki/List_of_country_calling_codes][1]
Take a look at the link above on country calling codes, and specifically see the section "Tree List".
One solution would be to implement a schema in Mongo based on this tree in order to decode the country codes.
So, a table could be created to store Mongo documents containing a field "1x" "2x" "21x" etc (the Y axis in the Tree List table).
Each of these documents could contain an array of sub-documents from x=0 to x=9 (the x axis in the Tree List table). The sub-document can contain the country name/code you are looking for. You can use a direct index into the array in the Mongo document for an efficient lookup.
I think you'll find this to be a pretty efficient implementation and should cover all the bases.
If you can restructure your array to an object this would be the fastest
const countries =
{
971: 'UAE',
1: 'USA',
44: 'UK',
}
;
var code = 44;
console.log(countries[code]);
const countries = [
{
name: 'UAE',
callingCode: 971
},
{
name: 'USA',
callingCode: 1
},
{
name: 'UK',
callingCode: 44
}
];
var myFound =countries.filter(myFunc.bind(this,44));
function myFunc(code,element) {
if(element.callingCode == code){
return element;
}
}
console.log(myFound);
On MongoDB v 4.2 - you can use $let & $regexFind to do this :
db.collection.aggregate([
{
$match: {
$expr: {
$eq: [
{
$let: {
vars: {
value: {
$regexFind: {
input: "971524500000", // pass in as string
regex: { $toString: "$callingCode" }
}
}
},
in: "$$value.idx",
}
},
0
]
}
}
}
]);
Test : MongoDB-Playground
Explanation :
General Use-case :
In general regex searches - Will have an input which will be sub-string of actual string, Ex.:-
Actual string in DB : 'We can do it in mongo'
Input : mongo (/mongo/ - will work)
Your Use-case :
From above case as mongo exists in actual string/value of db field then you can get that document, But your case is different :
Actual string in DB : mongo
Input : 'We can do it in mongo'
This doesn't work that way, So using normal /We can do it in mongo/ isn't going help you here (Also doing few tricks with regex). So we need to make a trick to $regexFind operator. Unlike mongo documentation we need take 971524500000 into input field & regex as string value of callingCode field which is vice-versa to what's given in documentation.
So once we do that, We would get something like below :
{
"match" : "971", /** value of callingCode field */
"idx" : 0, /** Index of `971` in '971524500000' */
"captures" : []
},{
"match" : "1",
"idx" : 2,
"captures" : []
},
null /** 3rd doc no match */
As country code has to be at first of given number we need docs where "idx" : 0 - So we're using $let to get index of returned object & checking against 0 & eventually getting respective docs using $match.
Note :
There is something you need to look into, Just in case if you've docs like below :
{
"_id": ObjectId("5e8f67091aa1cc3d2158ade1"),
"name": "USA",
"callingCode": 1.0
},
{
"_id": ObjectId("5e8f67091aa1cc3d2158ade3"),
"name": "somecountry",
"callingCode": 197.0
}
& input is 1971524500000, then this query will bring both docs in result. This will be the case you need to check on. Anyhow I would suggest to try this query, rather than getting all documents for collection to the code & extract required o/p this might be better to do.

NodeJS/AngularJS - Reading Array of Objects from JSON

I've got an issue reading a nested array from JSON(BSON from MongoHQ) using Node and Angular.
JSON snippet: http://pastie.org/9305682. Specifically look for the edges array.
Mongoose model: http://pastie.org/9305685
Basically I call the character from the DB and then attempt to log it to the console with
console.log(char); before sending it back to the angular call with res.json(char); 'char' is the returned character from the databased saved as my mongoose model.
Attempting to log the character to the console. I get everything looking normal except for the portions with the nested "effects" arrays. Anywhere they show up I receive the following:
edges:
[ { name: 'Super Hacker', notes: '', effects: [Object] },
{ name: 'Witty', notes: '', effects: [Object] },
{ name: 'Attractive', notes: '', effects: [Object] },
{ name: 'Encyclopedic Memory',
notes: 'Prereq: d8 Smarts',
effects: [Object] },
{ name: 'Daywalker', notes: '', effects: [Object] },
{ name: 'Tough', notes: '', effects: [Object] } ],
From here if I try to call it with:
From NodeJS - console.log(char[0].edges[0].effects[0].type); - Returns undefined.
From Angular View - {{cur_char.edges[0].effects[0].type}} - Displays nothing.
Thanks in advance for the help. Let me know if I can provide more in.
I think what you're asking is how to see more depth to the object in the console output. You can use util.inspect to print out more information:
console.log(util.inspect(char, { depth: 5 }));
By default util.inspect only goes to a depth of 2 which explains why you can only see the contents of the array (1) and the primitive properties of each element in the array (2).
See: http://nodejs.org/api/util.html#util_util_inspect_object_options

Categories