gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 00:46:17 25 4
gpt4 key购买 nike

我想使用 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);
}
});

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

最佳答案

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

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

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

  • 第一次出现

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

关于javascript - 如何使用 Node JS 驱动程序创建新的 MongoDb 数据库,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34584003/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com