使用 mongodb 创建数据库 node.js

vkt*_*vkt 12 mongodb node.js

我可以使用 node.js 删除数据库,但我不知道如何创建新数据库?我想使用 node.js 创建 monogo 数据库。有人可以帮助我了解如何使用 node.js 创建 mongo 数据库吗?

小智 9

你可以这样做:

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();
});
Run Code Online (Sandbox Code Playgroud)


Rob*_*bie 7

这取决于您使用什么与 mongo 交互,但您通常不需要创建数据库。它通常是在您在代码中使用它时创建的。

例如,如果您使用 mongodb 本机驱动程序:

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.
});
Run Code Online (Sandbox Code Playgroud)

驱动程序 api 文档有很多示例 - http://mongodb.github.io/node-mongodb-native/2.0/api/


Ahm*_*rif 7

首先,通过运行此命令安装 MongoDB 模块。

npm 安装 mongodb --save

请记住,您不能仅创建数据库。您还必须创建集合才能查看新数据库。

索引.js

const mongodb = require('mongodb');
const uri = 'mongodb://localhost:27017';
const client = new mongodb.MongoClient(uri);

client.connect((err) => {
    if (!err) {
        console.log('connection created');
    }
    const newDB = client.db("YourNewDatabase");
    newDB.createCollection("YourCreatedCollectionName"); // This line i s important. Unless you create collection you can not see your database in mongodb .

})
Run Code Online (Sandbox Code Playgroud)

现在在终端中通过以下命令运行此索引文件

节点索引.js