How to execute dynamic MongoDB commands in Node.js? - node.js

For a special case, I need to dynamically construct various MongoDB driver calls, e.g
comand = "db.collection.find({name: "doe"})"
which must then be passed to the mongodb driver, e.g.
var db = MongoClient.connect("mongodb://..../test");
var result = eval(command);
console.log(result)
I have tried db.eval(), eval() and runCommand() without success.
How can this be done?

Related

Mongodb finding a record by native id generated Node.js backend

First time working with MongoDB. This query works for me in cmd line:
db.secrets.update({_id: ObjectId("5f767cd481cea1687b3dbf86")}, {$set: {secret_rating: 5}})
However, updating a record using essentially the same query on my node server is not completing this task when pinged. Am I wrong in trying to query for a record like so in my model? ObjectId obviously isn't native to my server.
db.secrets.update({_id: "5f767cd481cea1687b3dbf86"}, {$set: {secret_rating: 5}})
Assuming you're using the Nodejs Mongodb driver and not some ORM (since it hasn't been specified), two points of concern:
As far as my knowledge serves, if you have a connection object to your desired database in the db variable, you cannot reference collections directly such as you've done with db.secrets; you must instead use the collection method like so:
const secrets = db.collection("secrets");
secrets.find({
/*your query here*/
}).then((results) => {})
So, unless you've assigned db.secrets with db.collection("secrets") you should be getting an error, Cannot read property "update" of undefined. But I'm going to assume you've got the collection object in db.secrets since you did not mention you're getting that error.
You seem to be using a string instead of an ObjectID object. You can import the ObjectID constructor from the nodejs driver like so:
const ObjectID = require('mongodb').ObjectID
Then in your query, you will have to make a new ObjectID to get the correct result:
db.collection("secrets").find({
_id: new ObjectID("5f767cd481cea1687b3dbf86")
}).then((results) => {})
NOTE: The ObjectID constructor will throw an error if the string supplied to it is not a valid, 24-char hex string, so, if you're getting the id string as an input from somewhere (say, as a parameter in an API or as a command line argument), you might want to wrap it in a function that handles that error.

Why can't I store a PriorityQueue into MongoDB

Recently I have decided to replace arrays with priority queues for storing my list of jobs for a user into MongoDB. I use NodeJS and ExpressJS for backend. The priority queue I attempted to store is from an external package which can be installed by running the following command in terminal:
yarn add js-priority-queue
For some reason the priority queue works perfectly prior to storing it into MongoDB. However, the next time I attempt to take it out of MongoDB and use it, its functionality is missing. I declare its type as Schema.Types.Mixed in the Schema. Am I doing something wrong or is it not possible to store instantiated class objects into MongoDB?
As far as I know, when you store things in MongoDB they are stored as extended JSON (EJSON) in binary format (BSON)
const { EJSON } = require('bson');
const test = EJSON.stringify({a: new Date(), foo:function(){console.log('foo');}})
console.log(test) // "{"a":{"$date":"2020-07-07T14:45:49.475Z"}}"
So any sort of function is lost.

Node.js mongoose advance Search get query from user

I'm trying to set raw query from node to mongodb with mongoose driver.
I got the query from user using javascript
var keys = $('#advance-search').val();
then I Post the keys to the node server and trying to using the query in find() like the following:
var search = req.query.keys || ""
Product.find(keys)...
the problem is the type of keys is String and find() need object
when I tried to convert keys to object by keys = JSON.parse(keys) I got exception because the mongo query not a valid Json format
example: {'product.price' :{ $in :[500,400,300,600]}}
so what is the best way to make a raw query from html to mongo by node js, and how I can filter this query before execution?

Node.js Mongo DB find query works weirdly

I'm using Node.js MongoDB native driver for this.
When I use condition directly in the find() it Works fine
db.collection('test').find({'age':'25'}).toArray().then((docs)=>{
When I assign condition to a variable and use it in find() it works fine.
var query = {'age':'25'};
db.collection('test').find(query).toArray().then((docs)=>{
But when I assign a value from input by user the query doesn't work as expected instead works as if no condition was specified.
var query = (`{'age':'${age}'}`)
db.collection('test').find(query).toArray().then((docs)=>{
I tried printing the query and I see it has the required condition {'age':'25'}
Any thoughts please help.
Try this:
var query = {'age': `${age}`}

How to use a variable in a Nodejs command

So i have some variables, that contains strings. I would like to access my mongodb using these strings, but of course it won't work if i just write it down like that:
...some db connection code
var x="name";
...find all data, then loop
..function(err,docs){
docs[i].x;
}
The queastion is, how can i access the X parameters of my collection.
You can use this way :
database.mydata[i][x];

Resources