I would like to iterate over multiple Mongo collections in meteor (server side). First I would like to check if a collections has any documents.
My code so far:
var isEmptyCollection = function(name) {
if(name.find().count() === 0) {
return true
} else {
return false
}
};
var mycollections = ["CollectionOne", "CollectionTwo", "CollectionThree"];
for (var i = 0; i < mycollections.length; i++) {
if (isEmptyCollection(mycollections[i])) {
} else {
var data = mycollections[i].find({},{fieldOne: 1}).fetch();
console.log(data);
}
I get this Error:
TypeError: Object CollectionOne has no method 'find'....
How can I iterate over collections / check in a loop if a collection has any values?
Your array of collections contains a lot of strings, but it should contain a list of collection objects. Try changing the array assignment to:
var mycollections = [CollectionOne, CollectionTwo, CollectionThree];
I'm assuming you've defined these using Mongo.Collection.
mycollections[i] would be the string "CollectionOne".
Use global[ mycollections[i] ] to get a reference to the actual collection.
E.g: global[ mycollections[i] ].find().count()
On the client window[ mycollections[i] ] would be it.
Related
I am trying to find a match inside this JSON array but I find it a bit complicated since it's a nested array of objects.
I'm not sure what I am doing entire wrong here:
The idea is that I have an array with a set of permissions and I want to return only the set of permissions that match the role:
var data = [{
"visitor": {
"static": ["page-one:visit", "home-page:visit", "login"]
}
}, {
"users": {
"static": ["posts:list", "posts:create", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
}, {
"admin": {
"static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
}]
var role = "admin"
for(var x=0;x <data.length;x++){
if(role === data[x]){
console.log("OLE, we got a match!" + data[x])
}
}
For some reason I just can't find a match. I just wanna return the full object like:
"admin":{
"static": ["posts:list", "posts:create", "posts:edit", "posts:delete", "users:get", "users:getSelf", "home-page:visit", "dashboard-page:visit"]
}
Here is a JS Bin Link.
You could use the .find function like below:
data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });
Given your role is the key of the object, you need to check if the object itself contains the role as a key, for this you'd use Object.keys(<object>).indexOf(role) where indexOf will return the value of -1 if it's not found and 0+ if found.
var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]
var role = "admin"
var admins = data.find(function(x){ return Object.keys(x).indexOf(role) > -1; });
console.log(admins);
if you wanted to accommodate for an array of different roles, you can use the following, easy to follow example.
var data = [{"visitor":{"static":["page-one:visit","home-page:visit","login"]}},{"users":{"static":["posts:list","posts:create","users:getSelf","home-page:visit","dashboard-page:visit"]}},{"admin":{"static":["posts:list","posts:create","posts:edit","posts:delete","users:get","users:getSelf","home-page:visit","dashboard-page:visit"]}}]
var role = ["admin", "visitor"];
var admins = role.map(function(role) { return getObjectsForRole(role); })
function getObjectsForRole(role)
{
return data.find(function(x){
return Object.keys(x).indexOf(role) > -1;
});
}
console.log(admins);
The above is pretty much the same as before, but we're mapping (.map) each role and calling a function which contains our call to the .find function.
I am using mongoDB for storing the data and retrieving the data. So I am getting response data. I can get particular object from comparing name,But when I want to compare _id.$oid then it is giving me undefined. I am sharing my code.
Array.prototype.getIndexBy = function (name, value) {
for (var i = 0; i < this.length; i++) {
if (this[i][name] == value) {
return i;
}
}
return -1;
}
var data = documents[documents.getIndexBy("_id.$oid", "33453223")]
console.log("----------updates-------->",data);
SAMPLE JSON
[
{"_id":{"$oid":"3426"},
"name":"peeter"
},
{"_id":{"$oid":"5a027"},
"name":"ken"
},
{"_id":{"$oid":"5999"},
"name":"karmal"
}
]
I am able to compare with name, But I want to compare with _id.$oid, When I am taking _id.$oid then It is giving me undefined value. I want to compare only with _id. I am referring link
find the array index of an object with a specific key value in underscore
If you are using lodash/underscore.js, you can use _.find
var users = [
{"_id":{"$oid":"3426"},
"name":"peeter"
},
{"_id":{"$oid":"5a027"},
"name":"ken"
},
{"_id":{"$oid":"5999"},
"name":"karmal"
}
];
var index = _.find(users, function(o) { return o._id.$oid == '5999'; });
console.log(index);
<script src="https://cdnjs.cloudflare.com/ajax/libs/lodash.js/4.17.4/lodash.js"></script>
I want to create a dummy json data and use it for highChart.
This is how I am creating json array
var summaryData = {
WestWorld:[
{"Jan":7894},
{"Feb":7845},
{"March":5826},
{"April":7930},
{"May":1589},
{"June":7891},
{"July":9724},
{"August":7403},
{"September":5566},
{"October":7733},
{"November":1186},
{"December":4456}
],
EastWorld:[
{"Jan":7410},
{"Feb":9512},
{"March":7520},
{"April":8510},
{"May":9965},
{"June":72580},
{"July":147},
{"August":4489},
{"September":6685},
{"October":7036},
{"November":8852},
{"December":4569}
]
};
Now I intend to use this data for drawing charts.I am able to retrieve the keys by doing so
for (var key in summaryData){
console.log(summaryData[''+key+'']);
}
It is consoling an two arrays each of twelve objects.
Can I create this json object in a better way & minimize the if & for loop to get it's keys & value
You can setup your JSON like so:
var summaryData = {
WestWorld: {
"Jan":7894,
"Feb":7845,
...
},
EastWorld: {
"Jan":7410,
"Feb":9512,
...
}
};
This way you can access anything directly, without having to loop through the arrays in WestWorld and EastWorld. For example:
summaryData.WestWorld.Jan => 7894
summaryData has two objects that are arrays and in this case array of objects.
This will retrieve one array and its length
console.log((summaryData.EastWorld).length);
Show the first array element which is an object with a single key:value
console.log(summaryData.EastWorld[0]);
to get its value
console.log(summaryData.EastWorld[0].Jan);
A function to retrieve each key:value pair
function show(world) {
var len = (summaryData[world]).length;
var obj = "";
var ii = 0;
for (ii; ii < len; ii += 1) {
obj = summaryData[world][ii];
for (var key in obj) {
console.log(key + ' ==> ' + obj[key]);
}
}
}
show("WestWorld");
show("EastWorld");
To be a true JSON each string need to be double quoted
check with an online JSON Validation..
Part of my json Array
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }, ......
When I console.log the element I'm getting
[Object, Object, Object, …]
0: Object
privacy: "public"
id: "1169341693"
1: Object
privacy: "private"
id: "803641223"
2: Object
privacy: "public"
id: "1300612600"
I also have a unique id I want to search for
var uniqueId = 803641223;
I want to find, in my videos array, the right id, and delete that whole array element. So In that case, I want my final videos array to contain only 2 object, instead of 3 :
var videos = $j.parseJSON('
[
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"public",
"id":"1300612600" }, ......
My problem is how to get in the array to do my splice. I prefer to do it with jQuery
Any help please?
You can use grep :
videos = $.grep(videos, function(e) { return e.id!='803641223' });
In vanilla JavaScript you could have used the similar filter function but it's not supported by IE8.
Please note that videos is a JavaScript array, it's not a JSON array, even if it was made by parsing a JSON string.
A non-jQuery solution that modifies the array in place:
var uniqueId = 803641223;
var videos = [
{ "privacy":"public",
"id":"1169341693" },
{ "privacy":"private",
"id":"803641223" },
{ "privacy":"public",
"id":"1300612600" }
];
function cleaner(arr, id) {
for (var i = 0; i < videos.length; i++) {
var cur = videos[i];
if (cur.id == uniqueId) {
arr.splice(i, 1);
break;
}
}
}
cleaner(videos, uniqueId);
http://jsfiddle.net/4JAww/1/
Note that this modifies the original array in place, such that the original videos array will have the items you want, and the one that matched the uniqueId will be gone (forever). So it depends on whether you want to be able to access the original array ever again, or are okay with modifying it.
It just loops through the elements of the array, compares the item's id property to the uniqueId value, and splices if they match. I use break; immediately after the splice because you seem to imply that the uniqueId can/should only appear once in the array since it's...unique.
Hello you can remove element with javascript splice function...
videos.items.splice(1, 3); // Removes three items starting with the 2nd,
It worker for me.
arrList = $.grep(arrList, function (e) {
if(e.add_task == addTask && e.worker_id == worker_id) {
return false;
} else {
return true;
}
});
It returns an array without that object.
Hope it helps.
I'm clueless. I have a JSON string like this which I need to check for a supplied "property" (postsome in the following example):
var index_file =
[{
"indexAB":[
{ "postsome": ["keyword_abc", "keyword_def"] },
{ "testsome": ["keyword_111", "keyword_222"] }
]
},{
"index_random": [
{ "postsome": ["keyword_abc"] }
]
}]
There my be any number of indices ("indexAB", "index_random") with n objects inside.
I need to "find" my property postsome but I cannot get it to work, because I'm struggling with the correct way of accessing the object.
So:
for (var i = 0, l = indices.length; i < l; i += 1) {
doc._id = "postsome",
index_name = "indexAB";
indices[i]["indexAB"]; // ok, returns object on correct iteration
indices[i][index_name]; // undefined
indices[i].indexAB[0][doc._id] // ok, returns undefined or keywords
indices[i][index_name][0][doc._id] // undefined
}
Question:
How can I access a nested object in loop using a variable name index_name?
This is not a direct answer to your question but I believe that it may actually help you more than giving you a complicated way to access values in your object.
If instead of this JSON object:
var index_file =
[{
"indexAB":[
{ "postsome": ["keyword_abc", "keyword_def"] },
{ "testsome": ["keyword_111", "keyword_222"] }
]
},{
"index_random": [
{ "postsome": ["keyword_abc"] }
]
}];
you would have this much simpler data structure:
var index_file =
{
"indexAB": {
"postsome": ["keyword_abc", "keyword_def"],
"testsome": ["keyword_111", "keyword_222"]
},
"index_random": {
"postsome": ["keyword_abc"]
}
};
then it would be much easier to access, using just:
var value = index_file.indexAB.postsome[0]; // no loops, no nothing
// value == "keyword_abc"
See: DEMO
I think that what you should change is your data model because currently it is something that is very far from the idea of JSON and it will always be very hard do access data in it.
A couple of issues
"indexAB" only exists on the first element in the array
you cannot have dots inside variable names.
I suggest you test whether indexAB is a property of the object before deferencing it further. See example below:
Fixed
var indices = index_file;
for (var i = 0, l = indices.length; i < l; i++) {
var doc_id = "postsome";
var index_name = "indexAB";
indices[i]["indexAB"]; // ok, returns object on correct iteration
indices[i][index_name]; // undefined
if ("indexAB" in indices[i]) {
indices[i].indexAB[0][doc_id] // ok, returns undefined or keywords
indices[i][index_name][0][doc_id] // undefined
}
}
index_name is undefined because the line prior to that raises an error
doc._id = "postname" // this causes an error
Just use a simple string
doc = "postname"