writing a logic to check if value exists - coldfusion

working on the data returned by code
Trying to add some logic that if the value exists, show it else put empty
<cfset myStruct = {
"access_token" : "#st.access_token#",
"id": "#res.names[1].metadata.source.id#",
"name" : "#isDefined('res.names') ? res.names[1].displayname : ''#",
"other" : {
"email" : "#res.emailAddresses[1].value#"
}
}>
Open in new window
its not clean and it throws error on line 3 which is ID, so what kind of isDefined or structkeyexists i can write if it exists add it, else put an empty value

You could try Elvis operator
Edit: Unless you really need the values as a string, you do not need to use pounds to output the values
Edit 2: Have updated the example to use the right comment
<cfset myStruct = {
"access_token" : "#st.access_token#" <!--- If you have numeric token and need it to be a string --->
, "id" : res.names[ 1 ].metadata.source.id ?: ""
, "name" : res.names[ 1 ].displayname ?: ""
, "other" : {
"email" : res.emailAddresses[ 1 ].value ?: ""
}
}>

Related

Get specific value from OData response in Postman

Can anyone of you can help me this:
i Have such response body from WebAPI:
{
"value": "Created: \"salesorder\" : \"22a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: \"vis1_postleitzahl\" : \"0d9344c7-a45d-e711-80c5-955c5ca2a164\"
Found 1 vis1_orts
Reusing: \"vis1_ort\" : \"92734f57-375e-e711-80c5-955c5ca2a164\"
Created: \"vis1_anschlussadresse\" : \"67a734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_anschlussobjekts
Created: \"vis1_anschlussobjekt\" : \"6ba734c3-bf5f-ec11-80e6-0050568d2958\"
Found 0 vis1_infrastrukturinformations
Created: \"vis1_infrastrukturinformation\" : \"6fa734c3-bf5f-ec11-80e6-0050568d2958\"
Found 1 contacts
Reusing: \"contact\" : \"22530f60-285f-ec11-80e6-0050568d2958\"
Found 1 competitors
Reusing: \"competitor\" : \"7841f8e7-c211-ea11-80cd-0050568d3968\"
[0000]: Information: OK
"
}
i'd like to get specific values from this response body e.g. 22a734c3-bf5f-ec11-80e6-0050568d2958 and store as a environment variable. Is it possible?
The first observation is that the response is a standard serialized structure. Even if we deserialise the JSON payload, the value of value is this string, that seems to represent a form of execution log:
Created: "salesorder" : "22a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussadresses
Found 1 vis1_postleitzahls
Reusing: "vis1_postleitzahl" : "0d9344c7-a45d-e711-80c5-955c5ca2a164"
Found 1 vis1_orts
Reusing: "vis1_ort" : "92734f57-375e-e711-80c5-955c5ca2a164"
Created: "vis1_anschlussadresse" : "67a734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_anschlussobjekts
Created: "vis1_anschlussobjekt" : "6ba734c3-bf5f-ec11-80e6-0050568d2958"
Found 0 vis1_infrastrukturinformations
Created: "vis1_infrastrukturinformation" : "6fa734c3-bf5f-ec11-80e6-0050568d2958"
Found 1 contacts
Reusing: "contact" : "22530f60-285f-ec11-80e6-0050568d2958"
Found 1 competitors
Reusing: "competitor" : "7841f8e7-c211-ea11-80cd-0050568d3968"
[0000]: Information: OK
To specifically resolve the value 22a734c3-bf5f-ec11-80e6-0050568d2958 we need to make a few assumtions:
the value we are looking for is in the First line
the value is contained inside double quotes
the quoted value is the entire line content after the last full-colon character ;
the name of the environment variable is FirstGuid
Given those assumptions, we can write a Tests script to run after the request:
var logValue = pm.response.json().value;
var lines = logValue.split(/\r?\n/);
var lineOneTokens = lines[0].split(':');
var guid = lineOneTokens[lineOneTokens.length() - 1].trim().replace(/"/g,"");
pm.environment.set('FirstGuid', guid);
References:
Scripting in Postman
JavaScript - split string by new line character
How to Get the Last Element of an Array in JavaScript
I want to remove double quotes from a String

How to query with conditionals in MongoDB

I am new to MongoDB and am learning how to query for multiple things at once with conditionals.
I have a database with a document called 'towns' that contains an id, name, population, date of last census, items it is famous for, and mayor. For example, this is what one of the towns looks like (please keep in mind, this is old, random data, nothing is up to date, it is just an example for me to learn):
{
"_id" : ObjectId("60232b0bbae1e5336c5ebc96"),
"name" : "New York",
"population" : 22200000,
"lastCensus" : ISODate("2016-07-05T00:00:00Z"),
"famousFor" : [
"the MOMA",
"food"
],
"mayor" : {
"name" : "Bill de Blasio",
"party" : "D"
}
I am trying to find all towns with names that contain an e and that are famous for food or beer.
I currently have this query:
db.towns.find({name: {$regex:"e"}}, {$or: [{famousFor:{$regex: 'food'}}, {famousFor:{$regex: 'beer'}}]})
If I split up the name and the $or expression, it works, but together I get errors like:
Error: error: {
"ok" : 0,
"errmsg" : "Unrecognized expression '$regex'",
"code" : 168,
"codeName" : "InvalidPipelineOperator"
Or, if I switch the query to db.towns.find({name:/e/}, {$or: [{famousFor:/food/}, {famousFor:/beer/}]}) I get the error:
Error: error: {
"ok" : 0,
"errmsg" : "FieldPath field names may not start with '$'.",
"code" : 16410,
"codeName" : "Location16410"
What am I doing wrong? Is it how I am structuring the query?
Thanks in advance!
Problem Is the syntax.
find({condition goes here}, {projection goes here})
You need to put all of your conditions within one curly brace.
db.towns.find({name: {$regex:"e"}, $or: [{famousFor:{$regex: 'food'}}, {famousFor:{$regex: 'beer'}}]})

MongoDB case insensitive query on text with parenthesis

I have a very annoying problem with a case insensitive query on mongodb.
I'm using MongoTemplate in a web application and I need to execute case insensitive queries on a collection.
with this code
Query q = new Query();
q.addCriteria(Criteria.where("myField")
.regex(Pattern.compile(fieldValue, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)));
return mongoTemplate.findOne(q,MyClass.class);
I create the following query
{ "myField" : { "$regex" : "field value" , "$options" : "iu"}}
that works perfectly when I have simple text, for example:
caPITella CapitatA
but...but...when there are parenthesis () the query doesn't work.
It doesn't work at all, even the query text is wrote as is wrote in the document...Example:
query 1:
{"myField" : "Ceratonereis (Composetia) costae" } -> 1 result (ok)
query 2:
{ "myField" : {
"$regex" : "Ceratonereis (Composetia) costae" ,
"$options" : "iu"
}} -> no results (not ok)
query 3:
{ "scientificName" : {
"$regex" : "ceratonereis (composetia) costae" ,
"$options" : "iu"
}} -> no results (....)
So...I'm doing something wrong? I forgot some Pattern.SOME to include in the Pattern.compile()? Any solution?
Thanks
------ UPDATE ------
The answer of user3561036 helped me to figure how the query must be built.
So, I have resolved by modifying the query building in
q.addCriteria(Criteria.where("myField")
.regex(Pattern.compile(Pattern.quote(myFieldValue), Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)));
The output query
{ "myField" : { "$regex" : "\\Qhaliclona (rhizoniera) sarai\\E" , "$options" : "iu"}}
works.
If using the $regex operator with a "string" as input then you must quote literals for reserved characters such as ().
Normally that's a single \, but since it's in a string already you do it twice \\:
{ "myField" : {
"$regex" : "Ceratonereis \\(Composetia\\) costae" ,
"$options" : "iu"
}}
It's an old question, but you can use query.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&");
This is working with aggregate and matches :
const order = user_input.replace(/[-[\]{}()*+?.,\\/^$|#\s]/g, "\\$&");
const regex = new RegExp(order, 'i');
const query = await this.databaseModel.aggregate([
{
$match: {
name : regex
}
// ....
Use $strcasecmp.
The aggregation framework was introduced in MongoDB 2.2. You can use the string operator "$strcasecmp" to make a case-insensitive comparison between strings.
It's more recommended and easier than using regex.

Testing if value is not blank using IsNull vs Len() vs NEQ ""

From a best-practice or performance standpoint which option is best to use for testing if a FORM value is not blank?
<cfif NOT isNull(FORM.Forename)>
OR
<cfif Len(Trim(FORM.Forename)) GT 0>
OR
<cfif FORM.Forename NEQ "">
I don't want the value to be valid if it has something silly like 4 blank spaces in it. I guess 4 blank spaces is not technically a NULL value?
The second
<cfif Len(Trim(FORM.Forename)) GT 0>
The first will not be null. Cf will receive an empty string or no form element.
The third is covered by the second.
You may need to wrap the form element with an isdefined depending on the form element type.
The problem with all of these examples is that the variable needs to exist or it errors (hence Kobby's "isdefined").
To get around missing FORM variables, attributes, etc. (and not have to isDefined test for them all of the time) I constantly use these custom "NULL" functions...
/* "NULL" functions are to assist with setting and returning variable values of the type you want,
whether they already exist or not ... for easy coding.
<cfif NULL("message") EQ "Optional message value" />
#message# now exists <cfif message EQ "Other value" />
<cfif boolNULL("form.optionalVariableName") />
#form.optionalVariableName# now exists as a boolean <cfif form.optionalVariableName />
<cfif valNULL("attributes.expectedNumericVariableName") />
#attributes.expectedNumericVariableName# now exists as a numeric <cfif attributes.expectedNumericVariableName GT 5 />
<cfif lenNULL("query.expectedNonBlankQueryOrStructureVariableName") />
*/
// List not last is all elements except the last
function listNotLast(list) {
// 2nd param is optional list delimiter
var delimiter = arrayLen(arguments) GT 1 ? arguments[2] : ",";
// If more than 1 element return the list without the last one
return listLen(list, delimiter) GT 1 ? listDeleteAt(list, listLen(list, delimiter), delimiter) : list;
}
// Sets and returns a string even if not defined (sets the variable to "" or a query as query.column[1] = "").
function NULL(v) {
// Override the default blank string with optional 2nd param
var NA = arrayLen(arguments) GT 1 ? arguments[2] : "";
// Variable v does not exist. We'll make it an empty string
if (!isDefined(v)) {
// Query vars are treated differently. Can fail if we're a struct. It looks like we want a query variable query.column_name
if (listLen(v, ".") GT 1 AND !listFindNoCase("caller,attributes,request,client,session,variables,cookie,cgi", listFirst(v, "."))) {
// If the query doesn't exist at all make a blank one (NA)
if (!isDefined(listFirst(v, "."))) {
setVariable(listFirst(v, "."), queryNew("NULL"));
}
// Now add the column name we want as a blank array (NA)
queryAddColumn(evaluate(listFirst(v, ".")), listLast(v, "."), [ NA ]);
}
// Non-query variables created here as a blank string (NA)
else setVariable(v, NA);
}
// Originally defined or not we just return our string value
return evaluate(v);
}
// Returns a numeric value even if not defined (sets the variable to 0). Override the set and return in second var. Uses the NULL and listNotLast functions.
function valNULL(v) {
if (!isDefined("NULL") OR !isDefined("listNotLast")) throw(type = "Missing function", message = "The NULL and listNotLast functions are required for the valNULL function.");
// Return a zero if non defined or non-numeric. Override here with 2nd param
var NA = arrayLen(arguments) GT 1 ? arguments[2] : 0;
var LE = listNotLast(v, ".")
// Use the NULL routine to ensure we're already created, test numericy
if (!isNumeric(NULL(v))) {
// We're non-numeric, check if its a query var (NULL will have created if need be)
if (isDefined(LE) AND isQuery(evaluate(LE))) {
// The query may need a row
if (!evaluate(LE & ".recordCount")) queryAddRow(evaluate(LE), 1);
// NULL already returned us a blank query with our column name if it didn't exist, just set our cell's NA (0) value here
querySetCell(evaluate(LE), listLast(v, "."), NA, 1);
// Non-query variables just set NA (0) value
} else setVariable(v, NA);
}
// Originally defined or not we just return our numeric value
return evaluate(v);
}
// Returns a boolean value even if not defined (sets the variable to false). Uses the NULL function. No overrides.
function boolNULL(v) {
if (!isDefined("NULL")) throw(type = "Missing function", message = "The NULL function is required for the boolNULL function.");
// Use the NULL function to return true for "1" values
if (NULL(v) EQ 1) setVariable(v, true);
// If its not boolean then its false. eg. 0, [blank], false, 'fasle' all set and return false
if (NOT isBoolean(NULL(v))) setVariable(v, false);
// Boolean only values returned here
return evaluate(v);
}
// Returns a string length even if not defined (sets the variable to "" and returns 0 length). Uses the NULL function. No overrides.
function lenNULL(v) {
if (!isDefined("NULL")) throw(type = "Missing function", message = "The NULL function is required for the lenNULL function.");
return len(NULL(v));
}

SpringMongo Case insensitive search regex

I am trying a case insensitive search in Mongo. Basically I want case insensitive string match I am using regex. Here is my code
Query query = new Query( Criteria.where(propName).regex(value.toString(), "i"));
But the above dosent match my whole string(a string sometime with spaces). It returns values even if its a substring.
Eg: Suppose my collection has 2 values "Bill" and "Bill status',It returns me "bill" even if my search is "bill status". It returns results even if the there is a sub string of the string I am searching for
I tried Query query = new Query( Criteria.where(propName).is(value.toString()));
But the above is case sensitive. Can someone please help on this.
Insensitive search using regex search. input_location could be Delhi,delhi,DELHI, it works for all.
Criteria.where("location").regex( Pattern.compile(input_location, Pattern.CASE_INSENSITIVE | Pattern.UNICODE_CASE)));
The regex /^bill$/i will match just against "Bill" in a case-insensitive manner.
Here is an example showing this (in the mongo shell):
> db.foo.insert({name: "Bill"});
> db.foo.insert({name: "Bill status"});
> db.foo.insert({name: "another Bill"});
> db.foo.find()
{ "_id" : ObjectId("5018e182a499db774b92bf25"), "name" : "Bill" }
{ "_id" : ObjectId("5018e191a499db774b92bf26"), "name" : "Bill status" }
{ "_id" : ObjectId("5018e19ba499db774b92bf27"), "name" : "another Bill" }
> db.foo.find({name: /bill/i})
{ "_id" : ObjectId("5018e182a499db774b92bf25"), "name" : "Bill" }
{ "_id" : ObjectId("5018e191a499db774b92bf26"), "name" : "Bill status" }
{ "_id" : ObjectId("5018e19ba499db774b92bf27"), "name" : "another Bill" }
> db.foo.find({name: /^bill$/i})
{ "_id" : ObjectId("5018e182a499db774b92bf25"), "name" : "Bill" }
However, a regex query will not use an index, except if it is left-rooted (ie. of the form /^prefix/) and if the i case-insensitive flag is not used. You may pay a substantial performance penalty over using a query that uses an index. As such, depending on your use case, a better alternative might be to use application logic in some way, for example:
Enforce a case when you insert items into the database (e.g. convert "bill" to "Bill").
Do a search against your known case (e.g. search just against "Bill").