How to create a new db in mongoose? How to create a new db in mongoose? mongoose mongoose

How to create a new db in mongoose?


It should not throw any error. The moment you insert a document in any new collection of that DB, the collection and db will be created


I found a solution for me when trying to connect by mongoose.

!!!First of all you need to specify database even if you want to connect to default db (default db is 'admin') it's important!!!Before I specified /admin db my data was mixing from several db.

You need to specify credentials (as username and password) for correct database (in my case admin (I never created admin db before, it's default db)).

But what to do if you want to connect to another database? You should feel authSource method in options of connection (specify another database in uri: mongodb://localhost:27017/database):

mongoose.connect(          mongoUri,          {            authSource: 'admin',            useNewUrlParser: true,            useUnifiedTopology: true,            useCreateIndex: true,            user: config.mongo.username,            pass: config.mongo.password,            serverSelectionTimeoutMS: 5000,          },          (err) => {            if (err != null) {              error('mongoose', err.message);            } else {              info('mongoose', 'mongoose connected');            }          },        )


In Mongoose, a new database record is created when new mongoStore() is invoked:

  app.use(session({    resave: false,    saveUninitialized: true,    secret: pkg.name,    store: new mongoStore({      url: config.db,      collection : 'sessions'    })  }));

or

const mongoStore = require('connect-mongo')(session);