Converting Mongo ID to String to do Comparison - javascript

I have a search feature that returns filtered data from my mongoDB based on a user's input for various filters. So, for instance I can do this and it works:
if (lastName) {
let arrlastName = [];
arrlastName = lastName.split(",");
_.each(arrlastName, (l, key, c) => {
arrlastName[key] = new RegExp(arrlastName[key], "i");
});
search['name.last'] = { $in: arrlastName };
}
The above returns a filtered data set where the results match whatever was passed in by the user in a comma separated list.
However, I am running into a challenge in comparing a user inputed value with an _id value in our mongo db. Of course, the _id I'm checking against here is not a string, but a mongo objectId -- that's the issue as far as I can tell. So I'm trying to figure out how I can convert either the input, or the _id, or both, to do a valid comparison. This was the initial code:
if (person) search['_id'] = person;
That doesn't work, because the value for person here is a string, and _id is not -- as I said, _id is a mongo objectId. So how can I do a type conversion to handle this check?
I tried this but it causes errors:
if (person) search['_id'].toString() = person;
What would the syntax look like for this kind of comparison?

In mongoDB you can use ObjectId.valueOf()
From the documentation
ObjectId("507c7f79bcf86cd7994f6c0e").valueOf()
will return the following string:
507c7f79bcf86cd7994f6c0e

Related

Filtering with an array of objects Regex in mongodb and mongoose

I'm trying to create a dynamic filter that can be implemented using at least 3 letters. I've got a lot of fields which i will be filtering against.
As an example, If I am trying to find users by email, I want to be able to type "#gma" or at least "gma" and ideally, it should return an array of all users containing the specified filtering value. This should be the same when searching for properties like firstName and so on
My current solution only works if I provide a full value that matches what I already have in my database. e.g test#gmail.com for email or john for firstName. I want to be able to type jo for the latter.
const regexPattern = new RegExp(["^", filterUsersByValue, "$"].join(""), "i");
const filteredU = UserModel.find({ [filterUsersBy]: regexPattern})
If I've understood correctly, since you are using JS you can create the find object like this:
let findObj = {}
findObj[userKey] = {$regex:userFilter, $options:"i"}
const filteredU = UserModel.find(findObj)
This creates que object like this:
const userFilter = "gma"
const userKey = "email"
let findObj = {}
findObj[userKey] = {$regex:userFilter,$options:"i"}
console.log(findObj)
What is the same that in this query

MongoDB javascript query; filter for value in in a column array

Using vanilla javascript, I'm using Mongo's dpd.js for querying the db.
In this snippet, I am trying find all matches for "design" in the column roleConsiderations within the collection techniques.
The values in roleConsiderations are in arrays - ["development", "design", "content"] and all of my different attempt to query for "design" fails.
dpd.js query results in empty response:
var query = {"roleConsiderations": "design"};
dpd.techniques.get(query, function (result) {
console.log(result);
});
Attempting to query through the url only returns exact matches (where "design" is the only value in the array).
http://my.mongo.db/techniques?roleConsiderations=["design"]
So how to query a mongodb column filtering for a value in an array?
You can use $in operator to specify the elements you want the returned objects to contain in specified field.
const query = { roleConsiderations: { $in: [ 'design' ] } };
Horrible syntax, I know, but it should work.
For more reading, please refer to this.

How to pass a Json array to JPQL Where clause for IN operator?

I've a multiple drop down select box available to select the list of genres. I'm creating a JSON array in JavaScript with all the genres selected by user & passing them to the back end Java function for plotting graph.
Database : MySQL
JavaScript:
var items = {};
$(function() {
$('#genres1').change(function() {
console.log($(this).val());
items.genres = $(this).val();
}).multipleSelect({
width: '56%'
});
});
var genres = items.genres.map(function(e){
return JSON.stringify(e);
});
var selectedGenres = genres.join(", ");
alert(selectedGenres); // Outputs : "Action", "Horror" and so on.... based on selection
Java:
public static void myFun(String genre){
Logger.info("Genre"+genre); //prints "Action","Horror"
List<String> selectedGenres = Arrays.asList(genre);
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
Logger.info("Genre"+selectedGenres); //prints ["Action","Horror"]
String queryString="SELECT wD FROM sed WHERE genre IN (:genres)";
Query query1=JPA.em().createNativeQuery(queryString).setParameter("genres", selectedGenres);
}
I'm not knowing how the array has to be passed to the query.
//List<String> selectedGenres = Arrays.asList("Action","Horror"); //Correct output
This hardcoded value gives me the correct output. When I pass the "selectedGenres" array containing exactly the same as above input - "Action","Horror"I don't get the preferred output. I also tried to send "genre" as it is as a parameter but it did not work though. I'm getting empty response. Can someone correct me where I'm going wrong?
List<String> selectedGenres = Arrays.asList(genre);
Some API clarification: Arrays#asList accepts String... vargs, where every argument is an element value to create the actual List.
Back to your method: your input argument is String genre (a String) while #asList method is not aware that this genre string is actually an array (and should not), and it does its job correctly - upon receiving a single element (a String in our case), a single-dimensional List is created.
To solve the issue, you may want to try one of those options:
(if your string is JSON array) Use JSON parsing library (such as Jackson)
Try to split the input (genre) by a comma, and transform that array back to List.

How do I "unstringify" a value within an array with javascript?

I'm building a dynamic search query for a Mongo database.
In short, and not directly related to the question... it looks like this:
var searchCriteria = {}; <-- start with empty object
return db.users.find(searchCriteria,
{ sort: { username: 1 }
});
The values for searchCriteria come from a search form, basically like this:
var filter = $(form).find('select[name=filter]').val();
var query = $(form).find('[name=query]').val();
searchCriteria[filter] = query <-- Using a dynamic key
Example output from the form:
console.log(searchCriteria);
>> { username: "jdoe" }
So here's my hangup. I need to "unstringify" the query within the searchCriteria, and turn it into this:
>> { username: /jdoe/ }
I've tried replace, among other things, but it keeps ending up as a string value. I need the /query/ in that format for the Mongo find query.
Any suggestions? Thank you :)
You can easily turn a string into a RegExp object by using new Regex(string).
Note that this is bound to have some security issues somewhere if you're passing in user input, but new RegExp shouldn't allow any arbitrary JS to run, but it could still crash your code by being an invalid Regex.
Source (MDN)

If i have a mongo document id as a string how do I query for it as an _id?

If i have a mongo document id as a string how do I query for it as an _id?
Will it work correctly to do .find({_id:'stringID'}) or do I need to convert it to a bson object first?
Do you mean you have the 24 hex digit string of an ObjectId?
Assuming that's what you mean, most drivers have a way to take a string and convert it to an ObjectId. In JavaScript that's:
.find({_id:new ObjectId("4f91bfcfaa7c5687a0c686d4")})
Updated to be a bit more useful for the node-native driver (from the documentation at https://github.com/christkv/node-mongodb-native):
// Get the objectID type
var ObjectID = require('mongodb').ObjectID;
var idString = '4e4e1638c85e808431000003';
collection.findOne({_id: new ObjectID(idString)}, console.log) // ok
collection.findOne({_id: idString}, console.log) // wrong! callback gets undefined
If your _id values are strings, you may query them just like any other field. (Just remember, if you are setting custom values for _id, they must be kept unique, or you will get a duplicate key error. )
Here is an example in the Mongo JS Shell:
> db.test.insert({_id:"stringID1"})
> db.test.insert({_id:"stringID2"})
> db.test.insert({_id:"stringID3"})
> db.test.find({_id:"stringID1"})
{ "_id" : "stringID1" }
>
Is this what you were looking for? I hope I did not misunderstand your question!
Mongoose auto casts the string _id to ObjectId when you use findByID, so you can query using the string _id.
Also remember that any input coming into your API from req.body or req.params will all be type string so you will need to type cast if needed..., but as mentioned, mongoose does that for you so you can just leave _id in the string format it comes in as.

Categories