Node+Mongo Native: generating request with sort - json

I'm creating step-by-step request for MongoDB. Everything is OK, but sort option cannot be recognized by Mongo. What I'm doing wrong?
var request = {}
request['show'] = 1;
request['category'] = category;
switch (sort) {
case "new_first":
request['sort'] = "[['time_added', -1]]";
break;
case "old_first":
request['sort'] = "[['time_added', 1]]";
break;
}
collection.find(request, function(err, posts) {
....
Thanks!

Found a solution:
sort_query = JSON.parse('{"sort":[["time_added",-1]]}')
It worked!

Related

Postman Object hasOwnProperty Tests

I am trying to evaluate a JSON, so that I can know if the properties are correct, I have the following code:
var data = JSON.parse(responseBody);
Object.keys(data).forEach(key => {
if(data.hasOwnProperty(key)){
console.log("Have all properties");
}
});
The problem I have is that, the answer is shown to me "n" times, how can I make it show it to me only once after evaluating that the properties exist?
This should do it:
var data = JSON.parse(responseBody);
let hasProperties = true;
Object.keys(data).forEach(key => {
if!(data.hasOwnProperty(key)){
hasProperties = false;
}
});
if (hasProperties) {
console.log("Have all properties");
}

Duplicate variable names in switch/case [duplicate]

I have the following code and I get the error 'Duplicate Declaration query_url'.
switch(condition) {
case 'complex':
const query_url = `something`;
break;
default:
const query_url = `something`;
break;
}
I understand that query_url is getting declared twice which isn't right. But i don't know how to resolve this. Can someone please help on what should be the correct way to make this work?
Try wrapping the cases in blocks:
switch(condition) {
case 'complex': {
const query_url = `something`;
… // do something
break;
}
default: {
const query_url = `something`;
… // do something else
break;
}
}
I personally prefer (and tend to abuse) the following in these sorts of cases:
const query_url = (()=>
{
switch(condition)
case 'complex': return 'something';
default : return 'something-else';
})();
(this requires ES6 or declaring "use-strict" in Node 4.x though)
Update: Alternatively, much more compact depending on if there is any logic there or if it's a simple assignment:
const query_url = {complex : 'something'}[condition] || 'something-else';
Also, of course, depends on the amount of outside-logic embedded in those switch statements!
if you need to redeclare the same variable in each case see #Bergi 's answer bellow
if query_url can have multiple values depending on the switch branch obviously you need a variable ( declare either with var or let ).
const is set once and stays that way.
example usage with let
let query_url = '';
switch(condition) {
case 'complex':
query_url = `something`;
break;
default:
query_url = `something`;
break;
}
You can use {} to scope your switch case.
For your case, you need to return the variable as long as the var exists and is accessible between curly braces:
switch(condition) {
case 'complex': {
const query_url = `something`;
return query_url;
}
default: {
const query_url = `something`;
return query_url;
}
}
If you won't use return, you must declare a let query_url above your switch statement.
Just put your switch in a function with some return statements :
var condition;
function aSwitch(condition){
switch(condition) {
case 'complex':
return 'something';
default:
return 'something';
}
}
const query_url = aSwitch(condition);
const query_url={
complex:'something complex',
other:'other thing'
}[condition]
The drawback is,you can't have default with object,you need to have addition check of condition.

Store.sync() lose extraParams

I have treeStore with extraParams
proxy: {
extraParams: {hierarchy_id: '5'},
api: {
update: jsonrpc.dim_hier.modifyData,
read: jsonrpc.dim_hier.getData,
create: jsonrpc.dim_hier.addData,
destroy: jsonrpc.dim_hier.deleteData
}
}
but store.sync() does not send to server this extraParams.
I tried to send param like this
component.getStore().getProxy().setExtraParam(
'hierarchy_id', hierarchy_id);
component.getStore().sync();
and this
component.getStore().sync({
params :{
hierarchy_id: hierarchy_id}
});
and
component.getStore().getProxy().setExtraParams({
hierarchy_id: hierarchy_id
});
component.getStore().sync();
but none of this works
What did I do wrong?
Thank for any help
In method doRequest (Ext.data.proxy.Direct)
if (action === 'read') {
params = request.getParams();
} else {
params = request.getJsonData();
}
I override this method like this
params = request.getParams();
if (action !== 'read') {
params.rows = request.getJsonData();
}}
Try it:
var store = component.getStore();
Ext.apply(store.proxy, {
extraParams: {
hierarchy_id: hierarchy_id
}
});
TO SEND THE extraParams ALWAYS NOT ONLY ON READ OPERATIONS (CREATE, DESTROY, UPDATE)
I extended
Ext.data.proxy.Direct
and override
doRequest
It worked like a charm.
Using ExtJs 4.1.1
The original code is:
if (operation.action == 'read') {
// We need to pass params
method = fn.directCfg.method;
args = method.getArgs(params, me.paramOrder, me.paramsAsHash);
} else {
args.push(request.jsonData);
}
I changed it to:
method = fn.directCfg.method;
args = method.getArgs(params, me.paramOrder, me.paramsAsHash);
if(operation.action !== 'read'){
args.push(request.jsonData);
}
Took the idea from here https://www.sencha.com/forum/showthread.php?282879-ExtraParams-Store-Create
Notice: your store will have a proxy of whatever you put on the alias of the class you created. Your alias will be like alias : 'proxy.mycompanydirect' then your store will have a proxy type 'mycompanydirect'

AS3 SharedObject IF isset or equals

very new to SharedObjects, but essentially all I want to do is let a user answer a question once and not allow them to answer again, how is it possible. This is what I have below?
/*if(_question.data.seenQuestion == "true") {
cookie_txt.text = "COOKIE FOUND";
} else {
cookie_txt.text = "NO COOKIES";
}*/
var _question:SharedObject;
_question.data.seenQuestion = "true";
_question.flush();
_question.close();
You're very close. It looks like you're not actually creating a SharedObject, to do that you would use the method getLocal:
var _question:SharedObject = SharedObject.getLocal("questionData");
Additionally, since SharedObject supports primitive types (String, int, Number, Object, Boolean, etc), you should store a Boolean instead of a String:
if(_question.data.seenQuestion)
{
cookie_txt.text = "COOKIE FOUND";
}
else
{
cookie_txt.text = "NO COOKIES";
}
_question.data.seenQuestion = true;
_question.flush();
Lastly, if you're using a local shared object (more common), you don't need to call close().
You do need to create your SharedOBject or else your code will throw errors:
var _question:SharedObject = SharedOBject.getLocal("myapp");
No need for flush or close just assign/change some data and that's it.
_question.data.seenQuestion = "true";
However SharedObject is not a good solution for persistent data. User can erase it/reset it, etc ...

nodejs parse mysql row to object

I'm a little newbie in node.js + mysql + object oriented.
Following question here I would like the 'Content' object to use the values returned by a mysql query. What I'm doing now I find it is really redundant and possibly stupid as rows[0] itself is the object I want to use. Any better way for doing this? Or different approach if this is wrong also appreciated.
(I'm using binary uuid keys that must be hex-stringifyed again to send as resource response)
content.js:
function Content() {
this.id = '';
this.name = '';
this.domain = '';
}
Content.prototype.validate = function(path, queryParams) {
...
return true;
};
Content.prototype.whatever = function(apiVersion, params, callback) {
...
return callback(null, newParams);
};
mysql.js:
MySQLDb.SELECT_CONTENT_ID = "SELECT id, name, domain FROM content WHERE id = UNHEX(?)";
MySQLDb.prototype.findContentByID = function(id, callback) {
this.dbConnection.query(MySQLDb.SELECT_CONTENT_ID, [ id ],
function(err, rows, fields) {
var content = new Content();
if (rows.length > 0) {
var i = 0;
for (var key in rows[0]) {
if (rows[0].hasOwnProperty(key) && content.hasOwnProperty(key)) {
// BINARY(16) --> HEX string
if (fields[i].columnType === 254) {
content[key] = rows[0][key].toString('hex').toUpperCase();
} else {
content[key] = rows[0][key];
}
} else {
console.log('Column ' + key + ' out of sync on table "content"');
}
i += 1;
}
}
callback(err, content);
});
};
contentRes.js:
contentRes.GETWhatever = function(req, res) {
db.findContentByID(req.params.id, function onContent(err, content) {
if (err || !content.validate(req.path, req.query)) {
return res.send({});
}
content.whatever(req.query.apiVersion, req.query.d,
function onWhateverdone(err, params) {
if (err) {
return res.send({});
}
return res.send(params);
});
});
};
I think a lot of people would say you are doing it generally the right way even though it admittedly feels redundant.
It might feel a little cleaner if you refactored your code such that you could call the Content() constructor with an optional object, in this case rows[0] although if you were keeping it clean you wouldn't have access to the fields so you would take a different approach to the data type conversion - either by selecting the HEX representation in query or simply having your Content() know it needs to convert the id property.
Keeping it fairly simple (by which I mean ignoring making the constructor a bit more intelligent as well as any error detection or handling), you would have:
function Content(baseObj) {
this.id = (baseObj && baseObj.id) ? baseObj.id.toString('hex').toUpperCase() : '';
this.name = (baseObj && baseObj.name) ? baseObj.name : '';
this.domain = (baseObj && baseObj.domain) ? baseObj.domain : '';
}
Then you could do something like this:
MySQLDb.prototype.findContentByID = function(id, callback) {
this.dbConnection.query(MySQLDb.SELECT_CONTENT_ID, [ id ],
function(err, rows, fields) {
if (err) return callback(err,null);
return callback(err, new Content(rows[0]));
});
You 'could' also grab the rows[0] object directly, HEX the UUID more or less in situ and modify the __proto__ of the object, or under Harmony/ES6 use the setPrototypeOf() method.
MySQLDb.prototype.findContentByID = function(id, callback) {
this.dbConnection.query(MySQLDb.SELECT_CONTENT_ID, [ id ],
function(err, rows, fields) {
if (err) return callback(err,null);
var content = rows[0];
content.id = content.id.toString('hex').toUpperCase();
content.__proto__ = Content.prototype;
return callback(err, content);
});
Note, I said you 'could' do this. Reasonable people can differ on whether you 'should' do this. __proto__ is deprecated (although it works just fine in Node from what I have seen). If you take this general approach, I would probably suggest using setPrototypeOf(), and install a polyfill until you are otherwise running with ES6.
Just trying to give you a couple of other more terse ways to do this, given that I think the redundancy/verbosity of the first version is what you didn't like. Hope it helps.