gpt4 book ai didi

javascript - 在MongoDB原生的NodeJS Driver中,什么时候使用MongoClient构造函数,什么时候使用Db构造函数?

转载 作者:IT老高 更新时间:2023-10-28 13:27:11 24 4
gpt4 key购买 nike

MongoClient 和 Db 构造函数在 manual 中描述。 .什么时候应该使用一个,什么时候应该使用另一个?

最佳答案

MongoClient 通常应该是首选,唯一的主要问题是它更新(1.2+)。

让我们引用 the manual:

MongoClient or how to connect in a new and better way

From driver version 1.2 we introduce a new connection Class that hasthe same name across all our official drivers. This is to ensure thatwe present a recognizable front for all our API’s. This does not meanthat your existing application will break, but rather that weencourage you to use the new connection api to simplify yourapplication development.

Furthermore, we are making the new connection class MongoClient acknowledges all writes to MongoDB, in contrast to the existing connection class Db that has acknowledgements turned off.

因此,两个最大的变化是 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();
});

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

关于javascript - 在MongoDB原生的NodeJS Driver中,什么时候使用MongoClient构造函数,什么时候使用Db构造函数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/17870215/

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