0

I want to create a new database at the time of the API call. I am already connected to one main database.

I have tried using mongoose.connect() method. And it gives me a positive response. But when I checked in mongo console I did not find the newly created database.

Here is my code.

const connectionString = `mongodb://${process.env.DB_HOST}:${
    process.env.DB_PORT
  }/client_${Math.random()
    .toString(36)
    .substring(2, 8)}`;

  mongoose.connect(
    connectionString,
    {
      autoReconnect: true,
      reconnectTries: 60,
      reconnectInterval: 10000,
      useNewUrlParser: true,
      useCreateIndex: true
    },
    (error) => {
      if (error) {
        console.log(error);
      } else {
        console.log('Connected');
      }
    }
  );

Hope you got my point. Looking for a solution.

1 Answer 1

1

As per mongodb documentation:

If a database does not exist, MongoDB creates the database when you first store data for that database. As such, you can switch to a non-existent database and perform the following operation in the mongo shell. link

This is true for mongo-shell as well, if you do use mydb; to create one and immediately do show dbs; it won't show up unless you create some data for that mydb like createCollection(), insert() etc.

So your code is alright because connect() is as good as use db;. Unless you create some data for that db you won't see that in mongo console.

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

3 Comments

Thanks for the response. Is there any parameter which will create a default collection while creating new Database?
@rahul If you were using node-native driver it would have been pretty simple as db.createCollection('collectionString', callback). But mongoose exposes the createCollection() on Model and does not create one unless you save/create one doc. Read more link
Thanks, let me try with this

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.