Reputation: 385
Can we create a mongoose query to return a result of a specific field data without space in between?
for example: series 'KA 04 A' and 'KA04A' is same. i want to make a check while adding a new series if the new series is already exist in my mongodb thru mongoose.
Currently my series field have space in between the current code of my mongoose is:
seriesModel.find({series_name:req.body.seriesName.toUpperCase(), status:'active'}, function(err, data){
if(err){
logger.info(err);
return false;
}
else if(data.length){
return res.json({error:true,message:'Series name already exists.'});
}
how can i return field data from db without space. so that i can make a check if the same series exists or not.
Upvotes: 2
Views: 1685
Reputation: 424
Ideally you would standardize your series_name
field before saving the record, using a custom hook that strips out whitespace.
That being said, you can use a regular expression in your query. For example, you can search for uppercase/lowercase variations on the word "mongoose" as follows:
model.findOne({name: /mongoose/i}, fn(){...});
One way to solve your problem would be to take your string, split it into individual characters, and then inject the whitespace pattern \s
between all the characters (I am assuming there is no leading or trailing whitespace in this field):
"^" + "KA04A".split("").join("\\s*") + "$" // "^K\s*A\s*0\s*4\s*A$"
(The start ^
and end $
are necessary so that we do not get false positives on e.g. "xKA04Ax")
Next, you would need to convert this string into the regex format ( /^K\s*A\s*0\s*4\s*A$/
) and plug it into your query:
model.findOne({name: new RegExp("^K\\s*A\\s*0\\s*4\\s*A$")}, fn(){...});
Major Caveat: you will need to be super careful that your original string only contains a-zA-Z0-9
and whitespace. It cannot contain anything that could be mistaken as a regex pattern without first escaping those characters (see here for more on this approach).
Upvotes: 1