繁体   English   中英

如何使用Node JS驱动程序创建新的MongoDb数据库

[英]How to create New MongoDb Database using the Node JS driver

我想使用Node JS驱动程序在MongoDB中创建一个新数据库。 我尝试了以下方法,但没有一个方法创建任何数据库(我使用mongo shell和RoboMongo检查了),最糟糕的是,它没有显示任何错误,下面的程序已成功执行,没有任何错误(我的意思是,错误是空值)

  • 第一种方法,使用Mongo Server

 var Db = require('mongodb').Db, Server = require('mongodb').Server; var db = new Db('myNewDatabase', new Server('localhost', 27017)); db.open(function (err, db) { if (err) { console.dir('ERROR we are in the callback of the open '); console.dir(err); throw err; } // Use the admin database for the operation var adminDb = db.admin(); console.dir('we are in the callback of the open'); db.close(); }); 

  • 我遵循的第二种方法是:

 var server = "localhost"; var port = 27017; var dbName = "myNewDatabase"; var mongodb = require('mongodb'); var mongoClient = mongodb.MongoClient; var connString = "mongodb://"+server+":"+port+"/"+dbName; mongoClient.connect(connString, function(err, db) { console.dir(err); if(!err) { console.log("\\nMongo DB connected\\n"); db.collection('test_correctly_access_collections', function(err, col2) { console.dir(err); if(err) { console.dir('Thier is a error in creating collection'); console.dir(err); } console.log("\\nColllection created succesfully\\n"); db.close(); }); } else{ console.log("Mongo DB could not be connected"); process.exit(0); } }); 

根据此链接 ,我们可以使用getDatabase API创建一个新的数据库,我尝试在Node JS中使用相同的API,但是找不到。

正如在google和stackOverflow中搜索的这个问题,但我只能找到很少的问题。 因此,我自己发布了答案。

首先感谢您@somallg,您是对的,我对您的评论投了赞成票。

答案是,您需要将文档插入集合中,然后,MongoDB将创建新数据库以及集合。 因此,我们可以将上述问题中的上述方法重写如下,以使用Node JS Driver创建新数据库:

  • 初审

 var Db = require('mongodb').Db, Server = require('mongodb').Server; var db = new Db('myNewDatabase', new Server('localhost', 27017)); db.open(function (err, db) { if (err) { console.dir('ERROR we are in the callback of the open '); console.dir(err); throw err; } var collection = db.collection("simple_document_insert_collection_no_safe"); collection.insert({hello:'world_no_safe'}); console.dir('we are in the callback of the open'); db.close(); }); 

  • 第二种方法

 var server = "localhost"; var port = 27017; var dbName = "myNewDatabase"; var mongodb = require('mongodb'); var mongoClient = mongodb.MongoClient; var connString = "mongodb://"+server+":"+port+"/"+dbName; mongoClient.connect(connString, function(err, db) { console.dir(err); if(!err) { var collection = db.collection("simple_document_insert_collection_no_safe"); collection.insert({hello:'world_no_safe'}); } else{ console.log("Mongo DB could not be connected"); process.exit(0); } db.close(); }); 

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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