how to pass string without double quotes inside mongodb query - javascript

I'm trying to pass a string to my mongodb query, but when it goes inside the query it adds double quotes to the string.
I'm passing this as a string to the criteria, because it is formed dynamically as a string:
str1={AccId:8,WSId:24237,CaseID:{$in:[4697516]},MEId:{$in:[4697523]},ConfigID:{$‌​in:[4697520]}}
var criteria = { str1 },
So when I'm passing this final criteria to db.coll.aggregate, it appends str1 and double quotes to the query.
query forming={"$match":{"str1":"{AccId:8,WSId:24237,CaseID:{$in:[4697516]},MEId:{$in:‌​[4697523]},ConfigID:{$in:[4697520]}}"}
query desired= {"$match":{AccId:8,WSId:24237,CaseID:{$in:[4697516]},MEId:{$in:[4697523]},Config‌​ID:{$in:[4697520]}}}
How can I get the desired query ?

What you really want to do is create the pipeline using object initializing methods like the bracket notation. Also, there's no need to use the $in operator with a single array element in your query, just query the field directly on the value.
Follow this example to get the concept:
var criteria = {
'AccId': 8,
'WSId': 24237,
'CaseID': 4697516,
'MEId': 4697523,
'ConfigID': 4697520
},
match = {};
match["$match"] = criteria;
db.collection.aggregate([match]);

Related

nodejs [] operator, avoid picking first char of array of strings

I have an array of strings that sometimes is an array that only contains one string.
when that is the case array[0] does not return the whole string but returns the first char in the string.
I can get around it with some if checking if length is > 1 but it is awful.
is there a safe [] operator or method that always return the whole string in position 0 of the array instead of the first char in the string?
This is an express input-based array in an html form.
I don't really have too much control over how it's generated.
i can't use a foreach as I have other parallel arrays from that form.
Before operating your var as an array, you should verify that it is an array.
In you case, i guess that when you get only a string the provider of your data return a string type and when there is more than one string it return an array of string.
So you need to verify the type returned by your data provider and then process with the right type.
if ( Array.isArray(yourVar) ) {
console.log('My var is an array');
} else {
console.log('My var is not an array');
}
You can also use typeof to check your var type, for example verify that your var is a string.

User list array filtering by containing the tag by RegExp in javascript

User list array filtering by containing the tag. I have an array of user list and I want to filter by tag contain using array filter match and RegExp for matching contain text its work but not get expected result.
let users=[{id:1,name:'john',tags:'a,b,c,v'},{id:2,name:'die',tags:'a,b,w,x'},{id:3,name:'ren',tags:'c,p,q,n'}];
let tagString='a,b,c';
let tagStringQuery = new RegExp(tagString, "i");
let data=users.filter((user) => user.tags.match(tagStringQuery)).map((user)=> user);
console.log('data',data);
O/P = [{id:1,name:'john',tags:'a,b,c,v'}]
but expected result is all user list which contains an 'a' or 'b' or 'c' tag.
This is really not a job for a regexp. Ideally you would have tags as Set instances, using intersection with a query Set to check for presence of tags.
If you insist on regexp though, you can't directly search for a,b,c to find if any of a, b or c is present: you would need to search for a|b|c (i.e. tagString.split(',').join('|')). If tags are of more than one letter, then you need to worry about substrings, so the search string should be \b(a|b|c)\b, and you should regexp-escape all the strings. And if you have multi-word tags or weird characters in them, you would need to search for ,(a|b|c), inside "," + user.tags + ",".
tagstring has to be 'a|b|c' instead of 'a,b,c' in case you want to apply or operator to those tags
Something like this should work fine without regex
let data = users.filter(x=>
tagString
.split(",")
.some(r=>
x.tags.split(",").includes(r)));

Extract Twitter handlers from string using regex in JavaScript

I Would like to extract the Twitter handler names from a text string, using a regex. I believe I am almost there, except for the ">" that I am including in my output. How can I change my regex to be better, and drop the ">" from my output?
Here is an example of a text string value:
"PlaymakersZA, Absa, DiepslootMTB"
The desired output would be an array consisting of the following:
PlaymakersZA, Absa, DiepslootMTB
Here is an example of my regex:
var array = str.match(/>[a-z-_]+/ig)
Thank you!
You can use match groups in your regex to indicate the part you wish to extract.
I set up this JSFiddle to demonstrate.
Basically, you surround the part of the regex that you want to extract in parenthesis: />([a-z-_]+)/ig, save it as an object, and execute .exec() as long as there are still values. Using index 1 from the resulting array, you can find the first match group's result. Index 0 is the whole regex, and next indices would be subsequent match groups, if available.
var str = "PlaymakersZA, Absa, DiepslootMTB";
var regex = />([a-z-_]+)/ig
var array = regex.exec(str);
while (array != null) {
alert(array[1]);
array = regex.exec(str);
}
You could just strip all the HTML
var str = "PlaymakersZA, Absa, DiepslootMTB";
$handlers = str.replace(/<[^>]*>|\s/g,'').split(",");

Regex matching to exclude beginning word

How can I make the following JavaScript
'id=d41c14fb-1d42&'.match(/(?![id=])(.*)[^&]/)[0]
return "d41c14fb-1d42"? It currently returns "41c14fb-1d42", without the beginning "d".
This should do it:
'id=d41c14fb-1d42&'.match(/^id=(.*)&$/)[1]
// "d41c14fb-1d42"
~ edit
When an original question does not give any context it is hard to guess what you need exactly, in which case I just give a solution that yields the requested output. I now understand you want to be able to parse a query string, i.e., name1=value1&name2=value2.... The following regular expression yields nameX followed by an optional =valueX, as I believe it is valid to provide just the parameter in a query string without a value.
var parameters = "id=foobar&empty&p1=javascript&p2=so".match(/\w+(=([^&]+))?/g)
// ["id=foobar", "empty", "p1=javascript", "p2=so"]
You can split on "=" to obtain parameter and value separately.
var param1 = parameters[0].split("=")
// ["id", "foobar"]
For a parameter without the value that would just yield an Array with 1 value, of course.
"empty".split("=") // ["empty"]
Note this assumes a query parameter to match \w+, if there are other cases you have to expand the regular expression.
If you only want to match the id parameter specifically anywhere in the query string and obtain its value, as I infer from your comment below, you can use:
"id=donald".match(/(?:^|&)id=([^&]+)/)[1]
// "donald"
"param1=value1&id=donald&param2=value2".match(/(?:^|&)id=([^&]+)/)[1]
// "donald"

get the matched data into array in javascript without using any loop

Problem background -- I want to get the nth root of the number where user can enter expression like "the nth root of x'.I have written a function nthroot(x,n) which return proper expected output.My problem is to extract the value of x and n from expression.
I want to extract some matched pattern and store it to a an array for further processing so that in next step i will pop two elements from array and replace the result in repression.But I am unable to get all the values into an array without using loop.
A perl equivalent of my code will be like below.
$str = "the 2th root of 4+678+the 4th root of -10000x90";
#arr = $str =~ /the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
print "#arr";
I want the javascript equivalent of the above code.
or
any one line expression like below.
expr = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/g,nthroot(\\$2,\\$1));
Please help me for the same.
The .replace() method that you are currently using is, as its name implies, used to do a string replacement, not to return the individual matches. It would make more sense to use the .match() method instead, but you can (mis)use .replace() if you use a callback function:
var result = expr.replace(/the\s?([+-]\d+)th\s?root\s?of([+-]\d+)/,function(m,m1,m2){
return nthroot(+m2, +m1);
});
Note that the arguments in the callback will be strings, so I'm converting them to numbers with the unary plus operator when passing them to your nthroot() function.
var regex=/the ([-+]?\d+)th\s?root\s?of\s?([-+]?\d+)/g;
expr=expr.replace(regex, replaceCallback);
var replaceCallback = function(match,p1,p2,offset, s) {
return nthroot(p2,p1);
//p1 and p2 are similar to $1 $2
}

Categories

Resources