5

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.

1 Answer 1

9

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!

Sign up to request clarification or add additional context in comments.

2 Comments

@karthik ponnam please accept the answer if it worked for you
Is it possible to set collection name dynamically through variables using mongoose?

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.