Get field value from mongoDB and assign to a var gives undefined - javascript

I am using MeteorJS and trying to get the value of a field from MongoDB and assign to a variable. But when want to print to console, it gives all the time 'undefined'. It works fine in HTML template, but i need to store the value in a var in .js file.
var num = ButtonsList.find({_id:'ZcLkjSwNGTpgHkoeq'});
var n = num.button1;
console.log("button number is: "+n);
The code below works fine by the way, if i want them to output in the browser. It outputs the buttons numbers in html using {{}} namespace. But as I said, i need to store the values in variables.
ButtonsList = new Meteor.Collection('list');
Template.theList.helpers({
'buttons': function(){
//return ButtonsList.find().fetch();
return ButtonsList.find('ZcLkjSwNGTpgHkoeq');
}
});

ButtonsList.find() returns a cursor.
ButtonsList.find().fetch() returns an array of buttons.
ButtonsList.findOne() returns will return a single button.
ButtonsList.findOne().fieldName will return the field fieldName of the button that was found.
The reason it works with the {{#each}} template block helper is that each blocks know how to iterate over cursors.

Your using Find , doesnt that mean your getting multiple reccords back? Shouldnt you be using FindOne instead? otherwise youll get an array of objects which means youd have to use num[i].button1 to get to the value.

Related

How to push an object in a object - javascript

I have two ways to fill the same hidden input in a form
Using an import CSV button
Adding data using another inputs
When I use the first option, the hidden input is filled with this
for example:
correct data
[{"url":"http://www.restaurant.com","businessTypeId":"1"},{"url":"http://www.hotel.com","businessTypeId":"2"}]
and works correctly if I store this data
but when I use the second option, the input is filled with this:
incorrect data
{"url":"http://www.google.com","businessTypeId":"3"}
That's incorrect because it doesn't have [brackets] at the beginning neither at the end
Another problem is when I insert data and fill that hidden input (with the first way) and then I try to add more data using the second way,
I get this
[{"url":"http://www.restaurant.com","businessTypeId":"1"},
{"url":"http://www.hotel.com","businessTypeId":"2"}],
{"url":"http://www.google.com","businessTypeId":"3"}
the first 2 data was inserted using the first way, the third data was inserted using the 2nd way
all data should be inside those brackets []
how can I "open" the brackets to push new data and "close" them?
at the beginning of all the code, the variable starts like this
let placesArray = [];
after the first method, data is inserted using this
placesArray.push(JSON.stringify(csvResult));
document.getElementById('places').value = placesArray;
them, after the second method, data is inserted using this
placesArray.push(JSON.stringify(placeData));
console.log('placeData datatable ' + placeData);
document.getElementById('places').value = placesArray;
Note: if I use the first method two times, brackets are duplicated, like this
[{"url":"http://www.restaurant.com","businessTypeId":"1"}
{"url":"http://www.hotel.com","businessTypeId":"2"}],
[{"url":"http://www.beauty-shop.com","businessTypeId":"3"},
{"url":"http://www.dentist.com","businessTypeId":"5"}]
I definitely need to "open" the object so that I can insert the new data and not go through this, how could I do that?
In the console.log, I have this for placeData [object Object], same result for csvResult, both are object
You could flatten the array before every value set
placesArray = placesArray.flat()
document.getElementById('places').value = placesArray;
Seems like csvResult is itself an array and as you stringify it and push it to placesArray, it doesn't look like the result you want.
I'd go with this instead
placesArray.push(...csvResult) // push each `csvResult` item into `placesArray`
document.getElementById('places').value = JSON.stringify(placesArray)
SOLVED:
I erased all JSON.stringify and added it to every line when I push data into inputs
like this
document.getElementById('places').value = JSON.stringify(placesArray);
in all lines when this is used.
thanks to #hgb123
for prevent to accumulate [brackets[more brackets]] I used .flat()
placesArray = placesArray.flat()
document.getElementById('places').value = JSON.stringify(placesArray);

How do I use #DbLookup results to populate a Readers field in xpages?

db = new Array("myserver", "myfolder\\mydb.nsf")
dir = getComponent("Dir").value;
div = getComponent("Div").value;
lu = #DbLookup(db, "ManagerAccess", dir + "PP" + div, "DTManagers");
var a = [];
a.push(lu);
var item:NotesItem = docBackEnd.replaceItemValue('FormReaders', #Unique(a));
item.setReaders(true);
That code is on the querySaveDocument ssjs. The result I get from the #DbLookup (when I put in a computed field) look like this:
Pedro Martinez,Manny Ramirez,David Ortiz,Terry Francona
I tried doing an #Explode(#Implode) thing on it, but it doesn't seem to work.
The error I get in the browser just tells me that the replaceItemValue line is broken.
To test it, I pushed several strings one at a time, and it worked correctly populating my FormReaders field with the multiple entries.
What am I doing wrong?
I see several problems here:
A. In cases as described by you #Dblookup in fact would return an array. If you push an array into a plain computedField control it will exactly look as that you wrote:
value1, value2, ..., valueN
A computedField doesn't know anything about multiple values etc, it just can display strings, or data that can be converted to strings.
If you want to test the return value you could try to return something like lu[0]; you then should receive the array's 1st element, or a runtime error, if lu is NOT an array. Or you could ask for the array's size using lu.length. That returns the number of array elements, or the number of characters if it's just a plain string.
B. your code contains these two lines:
var a = [];
a.push(lu);
By that you create an empty array, then push lu[] to the first element of a[]. The result is something like this:
a[0] = [value1, value2, ..., valueN],
i.e. a is an array where the first element contains another array. Since you don't want that, just use #Unique(lu) in your replaceItemValue-method.
C. I don't see why replaceItemValue would throw an error here, apart from what I wrote in topic B. Give it a try by writing lu directly to the item (first without #Unique). That should work.
D. for completeness: in the first line you used "new Array". A much better way to define your db parameters is
var db = ["myserver", "myfolder/mydb.nsf"];
(see Tim Tripcony's comment in your recent question, or see his blog entry at http://www.timtripcony.com/blog.nsf/d6plinks/TTRY-9AN5ZK)

javascript array show undefined when escape one index

I face a problem when tried to assign a value with a specific index. suppose I have javascript variable like
var track = new Array();
Now I assign a value for a specific index like-
track[10]= "test text";
now array has one value and it's length would be 1. But the main problem is it show it's length is 11.
alert(track.length); // 11 but I expect 1
and if I print its value then it shows like--
alert(track); // ,,,,,,,,,test text
and if I console this array then it show like below--
console.log(track); // undefined,undefined,undefined,undefined,.....,test text
I am very much confused because I assign only one value but it show 11. How it assign it's value and what characteristics array variable shows. Can anyone explain me and how to get its length 1 using below code--
var track = new Array();
track[10]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
The Array object automatically fills in the missing indexes. The reason it gives length 11 is because the index starts at 0.
If you are wanting to use key-value just use an object.
var track = {};
It will not have a .length value however.
javascript automatically fills in the array to push the element you want. You can get the "true" count by doing this:
track.filter(Boolean).length
However note that this will only "work" if you do not have any other elements that resolve to "false" value (eg. empty strings or setting them to false) so if you want to this, make sure you never actually set any other array elements to a falsy value so that you can use this convention. For example if you want to set other array values to a falsy value, use something like -1 instead as the thing to check.
Since you're setting the value for 10th position it's showing array size of 11
You must start from 0th position..
var track = new Array();
track[0]= "test text";
alert(track); // test text
alert(track.length); // 1
console.log(track); // test text
Try this
For such kind of operations i generally prefer the library called Underscore.js.
It abstracts array manipulations. You might want to checkout the compact method
Compact works like this:
_.compact([undefined, undefined, undefined, "test test"]) as ["test test"]
Then you can check the length of the returned array.
Though a simple approach is
filter(Boolean).length
But if you want to use the array then you might like underscore.

Checking for equivelance

OK, I'm missing something here and I just can't seem to find it because the logic seems correct to me, but I'm certain I'm not seeing the error.
var VisibleMarkers = function() {
var filtered = _.reject(Gmaps.map.markers, function(marker) {
return marker.grade != $('.mapDataGrade').val() && !_.contains(marker.subjects,$('.mapDataSubjects').val())
});
return filtered
}
I'm using underscore.js and jQuery to simplify my javascript work.
So right now, I'm checking by means of selects which data gets to be rejected and then I display the filtered markers on the (google) map (if it helps at all, this is using gmaps4rails which is working perfectly fine, its this bit of javascript that's making me lose the last of the hairs on my head).
Currently, the code functions 100% correctly for the ".mapDataGrade" select, but the ".mapDataSubjects" isn't. Now the markers object has a json array of the subjects (this is for students) and each item in the array has its ID. Its this ID that I am supposed to be checking.
Can someone see what I'm doing wrong?
If there's more info that needs to be included, please let me know.
This is on plain javascript on a RoR application using gmaps4rails
Now the markers object has a json array of the subjects (this is for students) and each item in the array has its ID. Its this ID that I am supposed to be checking.
_.contains compares a values, but it sounds like you want your iterator to compare a value to an object's "id" property. For that, _.some would work; it's like contains, except that, instead of comparing values, you can write the comparison as a function:
Returns true if any of the values in the list pass the iterator truth test.
Here's how you'd use it:
!_.some(marker.subjects, function(subject) {
return subject.id == $('.mapDataSubjects').val();
})
If I'm right, the whole line should be like this:
return marker.grade != $('.mapDataGrade').val() &&
// check that none of the subjects is a match
!_.some(marker.subjects, function(subject) {
// the current subject is a match if its ID matches the selected value
return subject.id == $('.mapDataSubjects').val();
});

how do I create list of unique values and systematically store them in localstorage

I'm trying to build a history list of clicked clicked page elements and store that list into HTML local storage, to be later displayed back to the user. The main pre-requisite is that the list cannot contain duplicates, so for example if the user clicks on item A and then on item B and again back on item A, only A and B are recorded. The third click is not recorded because it is not unique.
I'm also using persist.js.
I noticed that I am able to name the storage and give it a key and both are stored together in the real key of the localstorage thus: myStorageName>myKeyand my value is whatever I put there.
Here's the thing. I know you can store stringyfied JSON there but my list is built up from simple javascript variables one at at time.
I know what to do for the first click:
myStorageName.set(myKey, myCurrentElementId); // myCurrentElementId = this.id
now on the second click this is where I'm beginning to getting stuck. There is the original variable value already stored, now I want to append the new variable value. Assume that I can get the value from the store like this:
var dataExtract = myStorageName.get(myKey);
myObject = JSON.parse(dataExtract);
But how do I then turn this into a JSONstring -able thing (sorry I don't even know what it should be) that contains only a list of unique values. Does this make any sense to anyone?
First of all, you don't want to keep writing to/from localStorage everytime a link is clicked, because this'll slow down your page. Keep an updated Array populated with the element ids, then write to localStorage before the user navigates away from the page (by binding to the window's onbeforeunload event, for instance).
First:
var clickedLinks = []; // this Array will hold the ids of the clicked links
function uniqueClick(id){
return !~clickedLinks.indexOf(id); // this tests whether the id is already in the Array
};
In your click handler:
if(uniqueClick(this.id)){
clickedLinks.push(this.id); // append the new element id to the Array
}
Bind to window.onunload to save the Array before the user navigates from the page:
window.onunload = function(){
localStorage.setItem('clickedLinks',JSON.stringify(clickedLinks)); // stringify the Array and save to localStorage
}
To retrieve clickedLinks on subsequent page visit:
// convert the String back to an Array; try/catch used here in case the value in localStorage is modified and unable to be parsed, in which case clickedLinks will be initialized to an empty Array
try{
var clickedLinks = JSON.parse(localStorage.getItem('clickedLinks')) || [];
}catch(e){
var clickedLinks = [];
}
You may want to replace the first line (var clickedLinks = [];) with this last bit of code, as it will initialize the Array if it doesn't exist.
UPDATE:
IE8 does not support Array.indexOf. Alternatives might be:
use jQuery's $.inArray by replacing !~clickedLinks.indexOf(id); with !~$.inArray(id, clickedLinks);
Detect whether Array.prototype.indexOf is supported. If not, shim it with the code provided on this page.
Your model has an error. At the first time, you save a primitive value. Then, you want to "append" another value to it. Seems like you actually want to use an object:
var myObj = localStorage.getItem("myName");
if(myObj) myObj = JSON.parse(myObj); //Variable exists
else myObj = {}; //Elsem create a new object
function appendNewValue(name, value){
myObj[name] = value;
localStorage.setItem("myName", JSON.stringify(myObj));
/* Saves data immediately. Instead of saving every time, you can
also add this persistence feature to the `(before)unload` handler. */
}
I suggest to define in your code this:
localStorage.set= function(key,val)
{
localStorage.setItem(JSON.stringify(val));
}
localStorage.get = function(key,defval)
{
var val = localStorage.getItem(key);
if( typeof val == "undefined" ) return defval;
return JSON.parse(val);
}
and use them instead of get/setItem. They will give you ready to use JS values that you can use in the way you need.

Categories