I have array of string like this
let search = ["user","country"];
I want to get data from mysql database using LIKE operator.
For example like this
searchStmnt = `u.u_fullname LIKE "%` + search + `%"`
But the above code is not working. Can anyone suggest me how to do that?
const search = ["user", "country"];
const searchStmnt = search.map(item => `u.u_fullname LIKE '%${item}%'`).join(" OR ");
console.log(searchStmnt);
...or with REGEXP:
const search = ["user", "country"];
const searchStmnt = `u.u_fullname REGEXP '(${search.join("|")})'`;
console.log(searchStmnt);
Related
Let say I have dynamic array
const branddata = ["adidas", "nike", "puma"]
//this data can be sometime empty too like
// const branddata = []
//now I want to search all the product with brands like
const product = productmodel.find({brand:branddata})
The problem is, this thing works when branddata array is not empty and it gives me the product.
But when it is empty the find method search for a brand which is equal to "" and gives me zero product.
I want all the products to be displayed if branddata is empty.
How can I get this using $regex or any other?
you can check branddata is empty or not, and create query object based on it, like this
let q=(branddata && branddata.length>0 )?{brand:branddata}:{};
const product = productmodel.find(q);
when you have multiple params,you can do something like this
let params={
"brand":branddata,
"price":pricedata,
"gender":genderdata
}
let q={};
Object.Keys(params).forEach((t)=>{
if(params[t] && params[t].length>0 ){
q[t]=params[t]
}
})
const product = productmodel.find(q);
Finally found a solution with a function-based approach
$in is used to find document data which are in the array and $nin is used to find document data which are not in the array (basically when array is empty)
const branddata = ["adidas", "nike", "puma"]
const pricedata =["100"]
const genderdata =["male","female"]
const queryfunc = (value)=>{
var q = {}
if(value==''){
q["$nin"]=value;
}
else{
q["$in"]=key;
}
return q
}
const brand=queryfunc(branddata)
const price=queryfunc(pricedata)
const gender=queryfunc(genderdata)
const product = productmodel.find({brand,price,gender})
Suppose I have an array of object as:
const bookDetails = [{"author":"john","email":"john#gmail.com","readingTime":"121"},
{"author":"romero","email":"romero#gmail.com","readingTime":908},
{"author":"romero","email":"alpha#gmail.com","readingTime":1212},
{"author":"buck","email":"buck#gmail.com","readingTime":1902},
{"author":"buck","email":"bujor#gmail.com","readingTime":12125},
{"author":"romero","email":"romero#gmail.com","readingTime":500},
{"author":"john","email":"john#gmail.com","readingTime":10},
{"author":"legend","email":"legend#gmail.com","readingTime":12}
{"author":"john","email":"john#gmail.com","readingTime":1890}]
I have an object as:
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
I want to replace emailId with corresponding author.
So my expected O/P should be: {"romero":1212,"john":1248,"buck":909}
If anyone needs any further information please let me know.
You can generate a new object by iterating over bookDetails and look up the values from toMatch
Like this
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
const result = {};
for (const detail of bookDetails) {
const {email, author} = detail;
if (email in toMatch) {
result[author] = toMatch[email];
}
}
console.log(result);
Ah, you want to matching names from emails based on the array of objects. Is that right? If so..
const bookDetails=[{"author":"john","email":"john#gmail.com","readingTime":"121"},{"author":"romero","email":"romero#gmail.com","readingTime":908},{"author":"romero","email":"alpha#gmail.com","readingTime":1212},{"author":"buck","email":"buck#gmail.com","readingTime":1902},{"author":"buck","email":"bujor#gmail.com","readingTime":12125},{"author":"romero","email":"romero#gmail.com","readingTime":500},{"author":"john","email":"john#gmail.com","readingTime":10},{"author":"legend","email":"legend#gmail.com","readingTime":12},{"author":"john","email":"john#gmail.com","readingTime":1890}]
function namesMap(object,list){
//to save complexity(assuming the array is huge), I'd just loop through the list once to get the data I need
var obj={} //relates emails to names
list.forEach(item=>{
obj[item.email]=item.author
})
var toReturn={}
Object.keys(object).forEach(email=>{
toReturn[obj[email]]=object[email] //email to name conversion
})
return toReturn
}
//example usage
const toMatch = {"romero#gmail.com":1212,"john#gmail.com":1248,"bujor#gmail.com":909}
console.log(namesMap(toMatch,bookDetails))
There you go, I'm 100% you can do this easier, but this is the fastest response that came to my mind:
function changeData(bookDetails){
let returnableObject = {};
bookDetails.forEach(book => {
returnableObject[book.author] = book.readingTime
})
return returnableObject;
}
*EDIT -> This would work if your Author name IS UNIQUE if the author name is not unique you should change the name or maybe use an array of objects, not an object with multiple values...
*EDIT 2 -> I think I didnt understand your question.
I try to use MongoDB to operate searching of multiple searching strings.
The rule of multiple searching strings on MongoDB
db.meals.find({mealName: /fish/, mealName: /rice/, mealName: /spicy/})
The challenge of mine is that objects in Javascript can't not have the same key in same object.
I tried to way like this:
const str = "fish rice spicy";
const transform = (searchInput) => {
const searchField = {}
let searchArray = searchInput.split(" ");
searchArray = searchArray.map((item)=>{
const fixKey = "mealName";
searchField[fixKey] = new RegExp(item);
})
return searchField;
}
console.log(transform(str)); // {mealName: /spicy/}
In this condition
How do I conform the format of MongoDB multiple searching string in Javascript?
Just use mongoDB $in like this
const strArray = "fish rice spicy".split(" ");
db.meals.find({ mealName: {$in: strArray } })
It will fetches all records where mealName will matches any of the strArray item.
i'm recieving a serialzed data in the form as
error_message=%7B%0D%0A+null+%7D&systemId=53183&cert-id=176061&score=0&q2c=3%5C0&q2t=&answer_data=0000
how can i replace the = with : using typescript and replace should be for all the occurence of = except first that is error_message=value&systemId:value&cert-id=value and so on
i was trying with splice but it seems to be a long process and not that fast as the string grows.
You can do that by splitting the string by = and then treating the first element different from all others:
const input = 'error_message=%7B%0D%0A+null+%7D&systemId=53183&cert-id=176061&score=0&q2c=3%5C0&q2t=&answer_data=0000';
const repl = (inp) => {
const [firstEl, ...rest] = inp.split(/\=/); // Split by '='
return `${firstEl}=${rest.join(':')}`; // <first el> + '=' + <all other elements joined by ':'>
}
console.log(repl(input));
It looks like these are URL search query parameters, so you can get them in a more manageable format using the URLSearchParams constructor, then manipulate them however you want:
const queryString = 'error_message=%7B%0D%0A+null+%7D&systemId=53183&cert-id=176061&score=0&q2c=3%5C0&q2t=&answer_data=0000'
const [ first, ...rest ] = [...new URLSearchParams(queryString)]
.map(([k, v]) => [k, v].map(encodeURIComponent))
// assuming you still want URI encoding, else remove mapping
const result = [
first.join(':'),
...rest.map(x => x.join('=')),
].join('&')
console.log(result)
You can get the first '=' with the method indexOf(), then slice the string into the two different parts (one before the first '=' and one after) and replace the following equal signs
const string = "error_message=%7B%0D%0A+null+%7D&systemId=53183&cert-id=176061&score=0&q2c=3%5C0&q2t=&answer_data=0000"
const firstSignIndex = string.indexOf('=')
const result = string.slice(0, firstSignIndex+1) + string.slice(firstSignIndex+1).replace(/=/g, ':')
console.log(result)
Check this out, this will help you to replace the = with : except the first occurrence of = in your serialized string.
let a = 'error_message=%7B%0D%0A+null+%7D&systemId=53183&cert-id=176061&score=0&q2c=3%5C0&q2t=&answer_data=0000',
firstOcc = a.indexOf("error_message=") + 'error_message='.length,
starterStr = a.substring(0, firstOcc),
replacedStr = a.substring(firstOcc, a.length).replace(/=/g, ':');
console.log(starterStr + replacedStr);
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
You can make changes based on your needs firstOcc = a.indexOf("error_message=") + 'error_message='.length,
I have a string that could be in this form : 'school,room,teacher,pencil' or it could be 'school,room,teacher' .
What I want to do is after splitting the string , every word should have this structure :
{node:word,group:word-1,groupN:word-2 ...}
For example for the word room the structure would be {node:"room",group:"school"}
for the word teacher it would be {node:"teacher",group:"room",groupN:"school"}
for the word pencil it would be {word:"pencil",group:"teacher",groupN:"room",groupNN:"school"}
I did like that but it's not standard way :
var str="xxx,xxx,xxx,xxx"
var splitedStr = str.split(",")
for(var i=0;i<splitedStr.length;i++) {
var data = {node :splitedStr[i],group:splitedStr[i-1],groupN:splitedStr[i-2]}
}
Please do you have any idea how can i do that ?
Try this:
const getJson= (elName, textElements) => {
const elements = textElements.split(',');
const elementIdx = elements.findIndex(el => el===elName)
let result = {room:elName}
if (elementIdx>=0)
elements.slice(0,elementIdx).map((el, idx)=>{
result['group'+Array(elementIdx - idx).join("N") ] = el
})
return result
}
Ad use like this:
const arr = 'school,room,teacher,pencil'
console.log(getJson('room', arr))
console.log(getJson('teacher', arr))
console.log(getJson('pencil', arr))