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.
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>" .
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 });
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!
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With