简体   繁体   中英

Create new database with API call

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.

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.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM