簡體   English   中英

在MongoDB的本機NodeJS Driver中,何時使用MongoClient構造函數以及何時使用Db構造函數?

[英]In MongoDB's native NodeJS Driver, when to use MongoClient constructor and when to use the Db constructor?

手冊中描述了MongoClient和Db構造函數。 什么時候應該使用另一個?何時使用另一個?

MongoClient通常應該是首選,唯一的主要問題是它更新(1.2+)。

讓我們引用手冊:

MongoClient或如何以新的更好的方式連接

從驅動程序版本1.2開始,我們在所有官方驅動程序中引入了一個新的連接類。 這是為了確保我們為所有API提供可識別的前端。 這並不意味着您現有的應用程序會中斷,而是我們鼓勵您使用新的連接api來簡化應用程序開發。

此外, 我們正在建立新的連接類MongoClient確認對MongoDB的所有寫入,與已關閉確認的現有連接類Db形成對比。

因此,兩個最大的變化是MongoClient確認對DB的所有寫入以及在連接中選擇實際數據庫的事實。

使用MongoClient:

var MongoClient = require('mongodb').MongoClient
  , Server = require('mongodb').Server;

var mongoClient = new MongoClient(new Server('localhost', 27017));
mongoClient.open(function(err, mongoClient) {
  var db1 = mongoClient.db("mydb"); // The DB is set here

  mongoClient.close();
});

vs與Db:

// db is selected in the next line, unlike with MongoClient and most drivers to other databases
var db = new Db('test', new Server('locahost', 27017)); 
// Establish connection to db
db.open(function(err, db) {
  assert.equal(null, err);

  db.on('close', test.done.bind(test));
  db.close();
});

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM