Node.js Mongo DB find query works weirdly - node.js

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}`}

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.

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?

How do I input a NodeJS variable as a parameter in a MongoDB Query

I've read through every stack overflow I can find and I don't understand why this still isn't working.
I'm trying to construct a NodeJS Mongo find query and very simply want to use a variable as the values, the key does not need to be dynamic.
This is the code I was working with initially :
collection.find({project_id : project_id_val})
but this simply returns :
Found the following records
[]
I've also tried constructing my own javascript object and passing that in e.g.
Query = {}
Query["project id"] = project_id_val
collection.find(query)
But that doesn't work either, I know the key/value pair is correct because
project_id: "12345" works absolutely fine, and returns exactly what I want it to. I feel like this should be very simple so if someone could let me know where I'm going wrong that would be great.
Thanks.

sort mongodb collection by date in node.js

I’m new to mongodb and trying to figure out sorting with MongoClient in a node.js/express application.
This works in the mongo command line client:
db.mycollection.find().sort({"date":-1}); // displays by date, newest to oldest
I’m trying to achieve the same thing in my application:
db.collection('mycollection').find().sort({"date":-1}); //order remains the same
How can I achieve the same result as the first query? Thank you.
So, first, I'd recommend using Mongoose. Failing that, however, the Node MongoClient puts things like sorting into the find() arguments, like so:
db.collection('mycollection').find({}, {sort:{date:-1}});

How to execute dynamic MongoDB commands in 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?

Resources