single quote added to string when building a mongo string - node.js

I am trying to build query string to find documents in mongodb.
I have a variable assigned for the value in the key:value pair.
My code looks like below
var query = {"_id":orgId[0]};
var name = "_id";
console.log(query);
db.collection('orgs')
.findOne({query}, function (err,result) {
});
The value of query looks like the below
{ _id: '"567a701be4b017"' }
Its basically adding a single quote around the string value and therefor the result from the query is null. How can i get past this ?
Thanks
Sam

Related

I need to be able to obtain only the string that makes up the Id in a query to MongoDB

I'm using mongoDB, mongoose and typescript and I need to keep the document ids when I query but I can only get the type _id: new ObjectId("62aa4bddae588fb13e8df552") . I only need to keep the string "62aa4bddae588fb13e8df552" to later store it and do other processing. I can't get rid of the new ObjectId
async findById(id:string) {
const convert = {"_id":id}
const userfindById = await userModel.findById(convert);
const iD = userfindById?._id
return userfindById;
}
ObjectId is just a type :
https://www.mongodb.com/docs/manual/reference/bson-types/#std-label-objectid
If you want to get the string you can extract with _id.toString(), if you want to store the string you should change the type of _id (or create a new property)

Return all documents containing a certain field with mongoose

My schema has a string field companyName in my document.
I get an object from the query string as {companyName:"Amazon,Microsoft"}}.
How do I get back all documents that have company name either Amazon or Microsoft?
Right now I am changing the object to {companyName:{$regex:"Amazon Microsoft",$options:'i'}} and passing it to find() method but it is returning an empty array
You can transform your query string into $in operator:
let query = {companyName:"Amazon,Microsoft"};
let mongoDbQuery = { companyName: { $in: query.companyName.split(',') } }
let result = await Model.find(mongoDbQuery);

mongoose - field contained in string

I need to make the following query, I have a model in the db that holds a string. for example lets say that's the data:
[{ a : 'test/t' },
{ a : 'test/b' }]
Now I have the following string
var search = 'http://ttt.com/test/t'
I want to make a query which will find all the documents that 'a' property is contained inside the search variable, case insensetive.
All the exmaples I've seen talk about the opposite equation.
You can use the following query for the operation which uses the short for $where. Since this runs in Javascript, expect it to run slowly.
db.coll.find(function () {
var re = new RegExp(this.a.replace("/", "\/"))
return 'http://ttt.com/test/t'.match(re)
});

node.js: compare array of ObjectIds with a string object id or an array of string ObjectIds

My Schema is:
var schema = new Schema({
players: {
type: [Schema.Types.ObjectId]});
I'm using Promises. My simple query to fetch the collection by id is:
MyModel.findById(id).exec()
.then(function (doc) {
//here I'm getting my doc
})
.catch(next)
I'm getting my document but the problem is here I'm getting an array of ObjectIds and I want to compare this array of ObjectIds with an ObjectId which I have in the string form. In one case I want to find the index of this string id in that array of ObjectIds.
I tried by lodash like
var index = _.indexOf(doc.players, idInStringForm);//getting -1 as response
also tried with
var index = _.indexOf(doc.players.toString().split(","), idInStringForm);//it is working
but when I needed to take union of ObjectIds' arrays the above logic fails for example:
var arrayOfIds = _.union(doc.players.toString().split(","), stringArrayOfIds);
the above is not working because when doc.players is empty the arryaryOfIds also contains " " which fails my one of queries.
Does we have any better/common solution for the above cases or we need to go with if-else check?
You can filter out any empty strings before checking the union of the array and the id.
function removeEmptyStrings(value) {
return value != "";
}
array = array.filter(removeEmptyStrings);
Wherever the array value is equal to an empty string it will remove it from the array.
See the documentation for the filter method here: Filter
Why not Array.prototype.map and then union?
_.union(doc.players.map((player) => player._id), stringArrayOfIds)

find function in mongodb and literal objects

I use Mongoose on nodeJS and I have the following schema in MongoDB:
var users = new Schema({
local: {
user_uuid: String
,user_name: String
,password: String
,email: String
,connectionKey: String
}
});
And I'm exporting the schema in the following way:
module.exports.users = mongoose.model('users',users);
and this is my find statment:
var AllSchemas = require('../schemas/schemas');
...
AllSchemas.users.find({ user_uuid: doctorId},function(err,obj){
...
}
but I get that the user is not found.
If I take all the parameters out of the literal object "local" it will work
I want to know how can I find things inside a literal object.
You need to use dot notation to reach inside of embedded documents in your query:
AllSchemas.users.find({ 'local.user_uuid': doctorId }, function(err,obj) {
...
}
While referring to a sub object in the schema, you should use the dot notation inside quotes.
Please refer the following link to get the more information about the dot notation
http://docs.mongodb.org/manual/core/document/#document-dot-notation
In your case, you should use:
AllSchemas.users.find({ 'local.user_uuid': doctorId},function(err,obj){
...
}
This query will return you all the documents having user_uuid equal to doctorId.

Resources