YDN-DB How to verify if a record exists? - javascript

I'm trying to verify if a specific record exist inside a table by a given ID. For example:
var id = 23;
db.count('products',id).done(function(count) {
if(count>0){
db.get('products',id).done(function(r) {
//Do something
});
}else{
alert('No product found');
}
});
When I try this, I get the following error: uncaught exception: null
I'd really appreciate your help Thanks!.

Your solution is almost correct.
In IndexedDB API, there is no exists method, probably because it can be emulated using count method. But count method accepts only key range, so existence test should be:
var id = 23;
db.count('products', ydn.db.KeyRange.only(id)).done(function(cnt) {
if (cnt) { // exist
} else { // no exist
}
});
Another reason, exists method don't exist in the IndexedDB api is that, get don't give error for non-existing key. So you can safely, and recommended, to do:
var id = 23;
db.get('products', id).done(function(product) {
if (product) { // exist
} else { // no exist
}
});
I would like to point out that, in these two ways to detect existence, the first method is more efficient because it avoid deserialization. So if you just need to test for existence, use first method. For retrieving a record, which may or may not exist, use second method.
EDIT:
To query a record by primary key, id, or unique secondary key, sku
/**
* #param {string} id id or sku
* #param {Function} cb callback to invoke resulting record value. If not exists in the
* database, null or undefined is returned.
*/
var getByIdOrSku = function(id, cb) {
var req = db.get('items', id);
req.done(function(item) {
if (item) {
cb(item)
} else {
db.values('items', 'SKU', ydn.db.KeyRange.only(id), 1).done(function(items) {
cb(items[0]); // may not have result
});
}
});
};
If you prefer promise way:
db.get('items', id).then(function(item) {
if (item) {
return item;
} else {
return db.values('items', 'SKU', ydn.db.KeyRange.only(id), 1).done(function(items) {
return items[0];
});
}
}).done(function(item) {
// result query as as id or SKU
console.log(item);
});

Related

Invalid-key request passed to a map to retrieve the value. Handle this exception

I have a map, and am trying to retrieve a value based on the key passed in the form of "id". However in some cases, the "id" that is passed is invalid i.e. it is not present in the Map, which in turn makes the application crash. Is throwing the Error causing this issue ? I tried experimenting with the try-catch but it still continued to malfunction i.e. the screen stops loading on detecting this error. Not sure if I wrote the try-catch correctly. how do I best handle this to stop the application from malfunctioning in such a case and continue loading the screen.
Failed approach:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
var item = this.hmItems[id];
if (!item)
throw new Error("'Illegal argument: id=" + id);
return item;
};
Another failed approach:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function (id) {
try {
var item = this.hmItems[id];
if (!item) throw "illegal id!!!!!!!!!";
return item;
} catch(err) {
//log exception
}
}
Use hasOwnProperty to see if the property exists on the hmItems object:
this.hmItems = {}; //Map<Integer,Item>
Address.prototype.getItem = function(id) {
if (!this.hmItems.hasOwnProperty(id)) {
throw new Error("'Illegal argument: id=" + id);
}
return this.hmItems[id];
};
Just checking var item = this.hmItems[id]; if (!item) isn't a good test because it'll fail even if the property exists on the object but is falsey, like 0 or null.
Live demo:
class Address {
hmItems = {
1: 10,
2: 0
};
getItem(id) {
if (!this.hmItems.hasOwnProperty(id)) {
throw new Error("'Illegal argument: id=" + id);
}
return this.hmItems[id];
}
}
const a = new Address();
// Works:
console.log(a.getItem(1));
// Works:
console.log(a.getItem(2));
// Throws:
try {
console.log(a.getItem(3));
} catch(e) {
console.log(e.message);
}

Meteor - Creating a variable within publish

I'm try to get the below publish function to work. I would like to retrieve all users who do not have a class that the current user has in their profile.classes array. What am I doing wrong here?
Meteor.publish('classes', function () {
var class = Meteor.users.find({_id: this.userId},{fields: {"profile.classes": 1}});
var users = Meteor.users.find({
roles:'is_student',
"profile.classes": { $ne : class }
}});
return users;
});
Assuming profile.classes holds an array of strings and that you want to get all users who DO NOT have a class in the current user's classes, here is some code to do what you're asking for:
Meteor.publish('classes', function ( ) {
var user = Meteor.users.findOne({_id: this.userId},{fields: {"profile.classes": 1}});
if( user && user.profile && user.profile.classes ) {
return Meteor.users.find({ roles: 'is_student', 'profile.classes': { $nin: user.profile.classes } });
} else {
return this.ready();
}
});
The important line of that code is:
return Meteor.users.find({ roles: 'is_student',
'profile.classes': { $nin: user.profile.classes } });
The key part here is the $nin. From MongoDB documentation:
$nin selects the documents where:
- the field value is not in the specified array or
- the field does not exist.
So this should select users who either don't have a profile.classes array field, or have none of the classes the current user has.

meteor collection.update is not updating document

I am trying to trigger an update within a client method (thinking to move into server later) as follows:
Meteor.methods({
// Calling this and passing in a currentSelected value = "avatar" on click
'updateSelectedDocument' : function(currentSelected) {
var current = LayoutVariations.findOne({elementID: currentSelected});
var index = current.currentIndex;
myCollection.update({_id :current._id}, {currentIndex: 2});
}
});
The .update should find the document and update that document's currentIndex property, which is an integer.
I ran the myCollection.update({_id :current._id}, {currentIndex: 2}); in the console by passing in the _id (e.g. "GRvujvgBEmem3Dp3d") and it works. It's just not updating when I call it within a method and it's not throwing any errors.
Wondering what could be the issue.
Use the $set operator in your update to replace the value of the field currentIndex with the specified :
Meteor.methods({
// Calling this and passing in a currentSelected value = "avatar" on click
'updateSelectedDocument' : function(currentSelected) {
var current = LayoutVariations.findOne({elementID: currentSelected});
var index = current.currentIndex;
myCollection.update({_id :current._id}, {$set: { currentIndex: 2 } }, function(error, affectedDocs) {
if (error) {
throw new Meteor.Error(500, error.message);
} else {
return "Update Successful";
}
});
}
});

How to make 1 variable is equal to multiple values?

Hello I want to add friends on facebook using tokens..
I found this code.
edprens: function(a) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: USER ID/NAME I WANT TO ADD,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
},
example I have.. ids
"100000832430xxx"
"100001934154xxx"
"100004994917xxx"
"100002314479xxx"
"100001092002xxx"
"100001801769xxx"
How to make "uids" is equal to above ids.. so I can add them.?
Thank you
It's too big to post it in comment. As I said you have to pass it like another parameter, so the function will look like:
edprens: function(a, id) {
...
uids: id, // USER ID/NAME YOU WANT TO ADD
...
}
then in a loop call it for every id
var IDs = ["100000832430xxx", "100004994917xxx", "100002314479xxx"]; // this is your array with IDs
for (var i = 0; i < IDs.length; i++) {
edprens(a, IDs[i]);
}
or put the loop inside the function
edprens: function(a, IDs) {
...
for (var i = 0; i < IDs.length; i++) {
$.getJSON("https://graph.facebook.com/me/friends", {
...
uids: IDs[i], // USER ID/NAME YOU WANT TO ADD
...
});
}
...
}
edprens("ids###");edprens("ids###");edprens("ids###"); is not a loop. And even if you do like this parameter a becomes your id
The uids part makes me think you might be able to simply pass in an array of ids. Otherwise use a loop:
Here's it using a loop which should definately work:
//create an array with your ids
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
//loop through that array
$(myIds).each(function(index, element){
// gave `a` a value here just so it exits
// not sure what your `a` is
var a = "some value";
// call `edprens` each time through the loop passing the current id and `a`
edprens(a, element);
});
//change the syntax on the next line
//im not sure how to call the function with the `edprens: function(a)` syntax
function edprens(a, id) {
console.log('function would have been called with id:'+id);
// im commenting out the rest since it requires other code not present
/*if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: id,
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}*/
};
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
Here's it passing an array which might work?...:
//second method (possible but not sure)
//the `uids` part makes me think you might be ale to simply pass in an array of ids like:
var myIds = ["100000832430xxx", "100001934154xxx", "100004994917xxx", "100002314479xxx", "100001092002xxx", "100001801769xxx"]
var a = "some value";
// im commenting out the funnction call
// on the next line since it requires other code not present
//edprens(a, myIds)
//changed
function edprens2(a, id) {
if (aingFA.tueds.length >= 500 || a == "sisa") {
$.getJSON("https://graph.facebook.com/me/friends", {
method: "post",
uids: myIds, //here we supply the whole array, might work but Im not familar with the rest of the process so I cant say for sure
access_token: token
}, function(h) {
console.log(JSON.stringify(h))
});
aingFA.tueds = []
}
};

How to save my model using Parse cloud js?

I had a read of the meme example but it doesn't seem to update, just create new objects! What I want is to
a. find some given db table
b. update some fields in the db table
c. save the db table back to the database
Given this code, what is the missing piece so that I can actually update an object?
query.find(
function(results){
if (results.length > 0){
return results[0];
} else {
//no object found, so i want to make an object... do i do that here?
return null;
}
},
function(error){
response.error("ServerDown");
console.error("ServerDown - getModuleIfAny URGENT. Failed to retrieve from the ModuleResults table" + +error.code+ " " +error.message);
}
).then(
function(obj){
var module;
if (obj != null){
console.log("old");
module = obj;
module.moduleId = 10; //let's just say this is where i update the field
//is this how i'd update some column in the database?
} else {
console.log("new");
var theModuleClass = Parse.Object.extend("ModuleResults");
module= new theModuleClass();
}
module.save().then(
function(){
response.success("YAY");
},
function(error) {
response.error('Failed saving: '+error.code);
}
);
},
function(error){
console.log("sod");
}
);
I thought the above code would work - but it does not. When it finds an object, it instead refuses to save, stupidly telling me that my object has no "save" method.
First I would double check the version of the javascript sdk you're using in your cloud code. Make sure it's up to date e.g. 1.2.8. The version is set in the config/global.json file under your cloud code directory.
Assuming you're up to date I would try modifying your code by chaining the promises using multiple then's like so:
query.find().then(function(results){
if (results.length > 0){
return results[0];
} else {
//no object found, so i want to make an object... do i do that here?
return null;
}
},
function(error){
response.error("ServerDown");
console.error("ServerDown - getModuleIfAny URGENT. Failed to retrieve from the ModuleResults table" + +error.code+ " " +error.message);
}).then(function(obj){
var module;
if (obj != null){
console.log("old");
module = obj;
module.moduleId = 10; //let's just say this is where i update the field
//is this how i'd update some column in the database?
} else {
console.log("new");
var theModuleClass = Parse.Object.extend("ModuleResults");
module= new theModuleClass();
}
module.save();
}).then(function(result) {
// the object was saved.
},
function(error) {
// there was some error.
});
I think this should work. Fingers crossed. Cheers!

Categories

Resources