简体   繁体   中英

Create database node.js with mongodb

I am able to drop database using node.js but I dont know how to create new database? I want to create monogo database using node.js. Can someone help me about how to create mongo database using node.js?

you can do it this way:

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/mydatabase"; // mydatabase is the name of db 
MongoClient.connect(url, function(err, db) {
  if (err) throw err;
console.log("Database created!");
  db.close();
});

It depends on what you're using to interact with mongo, but you don't usually need to create the database. It's usually just created when you use it in your code.

For example if you use the mongodb native driver:

MongoClient.connect('mongodb://localhost:27017/myNewDatabase', function(err, db) {
  // If a database called "myNewDatabase" exists, it is used, otherwise it gets created.

  var collection = db.collection('myNewCollection');
  // If a collection called "myNewCollection" exists, it is used, otherwise it gets created.
});

The driver api docs have lots of examples - http://mongodb.github.io/node-mongodb-native/2.0/api/

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