Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to pass variable name as collection name for mongo db in nodejs

I am using node js and mongo db and I want to pass a variable to collections

var id = "someid";
db.collection(id).insert("some json data");

If I did like this it is giving me an error as collection name must be a string.

like image 376
Karthik Ponnam Avatar asked Sep 06 '16 16:09

Karthik Ponnam


People also ask

What is $$ in MongoDB?

Variables can hold any BSON type data. To access the value of the variable, prefix the variable name with double dollar signs ( $$ ); i.e. "$$<variable>" . If the variable references an object, to access a specific field in the object, use the dot notation; i.e. "$$<variable>. <field>" .

How does MongoDB connect to node js database?

To connect a Node. js application to MongoDB, we have to use a library called Mongoose. mongoose. connect("mongodb://localhost:27017/collectionName", { useNewUrlParser: true, useUnifiedTopology: true });


1 Answers

You can create variable using var for collection name

var colName = "mytest"

and then execute all the operations on collections as below:

db[colName].find()
db[colName].rename("newName")

etc. This will help you keep your collection name dynamic and can even update it keeping your commands same.

Hope this helps!

like image 131
Shumi Gupta Avatar answered Sep 27 '22 21:09

Shumi Gupta