简体   繁体   中英

How to create a new db in mongoose?

If I use Mongoose in node.js I need to do:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');

But what if I just installed mongodb and I don't have any DB at the moment? How can I create a new DB using mongoose in node.js before doing mongoose.connect('mongodb://localhost/myDB') ? Or if there is no such myDB then it will create a new one? or will throw an error that there is no such a DB?

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

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);

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