What's New新增功能¶
On this page
What's New in 4.14.1中的新增功能What's New in 4.04.0中的新增功能- TypeScript
Key Changes关键变化- Node.js Version
Cursor Improvements游标改进MongoClientOptions
InterfacecreateCollection()
BulkWriteError
→MongoBulkWriteError
DB
Collection.group()
Authentication认证GridStore
RemovalUnified Topology一致性拓扑Explain解释Command Monitoring指挥监视Detailed List详细清单What's New in 3.63.6中的新增功能
Learn what's new in:了解以下方面的新功能:
What's New in 4.14.1中的新增功能¶
New features of the 4.1 Node.js driver release include:4.1 Node.js驱动程序版本的新功能包括:
Added load balanced connection support for all cluster types including the beta Serverless platform.添加了对所有群集类型(包括beta无服务器平台)的负载平衡连接支持。Added support for the增加了对advanceClusterTime()
method to determine if theClientSession
should update its cluster time.advanceClusterTime()
方法的支持,以确定ClientSession
是否应更新其群集时间。
What's New in 4.04.0中的新增功能¶
New features of the 4.0 Node.js driver release include:4.0 Node.js驱动程序版本的新功能包括:
TypeScript¶
We've migrated the driver to TypeScript.我们已将驱动程序迁移到TypeScript。You can now harness the type hinting and intellisense features in editors that support it to develop your MongoDB applications.现在,您可以利用支持它的编辑器中的类型提示和intellisense功能来开发MongoDB应用程序。Enjoy the benefits of this work in pure JavaScript projects as well.在纯JavaScript项目中也可以享受这项工作的好处。The underlying BSON library used by this version is now migrated to TypeScript.此版本使用的基础BSON库现在迁移到TypeScript。Inline documentation is now consistenly formatted to improve display in editors.内联文档现在已一致性格式化,以改进编辑器中的显示。If you are a user of the community types如果您是社区类型@types/mongodb
, there will likely be issues adopting the types from our codebase. We could not achieve a one to one match in types due to the details of writing the codebase in TypeScript.@types/mongodb
的用户,那么采用我们的代码库中的类型可能会出现问题。由于在TypeScript中编写代码库的细节,我们无法在类型中实现一对一的匹配。
We'd love to hear your TypeScript related feature requests. 我们很想听听您对TypeScript相关功能的要求。Please submit ideas on our JIRA project here.请在此提交关于我们JIRA项目的想法。
Key Changes关键变化¶
Node.js Version¶
The minimum supported version of Node.js is now v12.9 or greater for version 4 of the driver. 对于驱动程序版本4,Node.js的最低支持版本现在是v12.9或更高版本。Support for our 3.x branches will continue until summer 2022 to allow time to upgrade.对我们3.x分支的支持将持续到2022年夏季,以便有时间升级。
3.x supports back to Node.js v4.3.x支持返回Node.js v4。
Cursor Improvements游标改进¶
Our Cursor implentation is now updated to make it clear what is possible before and after execution of an operation.我们的游标实现现在已经更新,以明确在执行操作之前和之后可以做什么。
const fc = collection.find({a: 2.3}).skip(1)
for await (const doc of fc) {
console.log(doc)
fc.limit(1) // incorrect usage, cursor already executing
}
There was inconsistency surrounding how the cursor would error if a setting was applied after cursor execution began. 如果在游标执行开始后应用设置,则游标将如何出错,存在不一致性。Now, the cursor will throw an error when attempting to apply operations in an invalid state, similar to the following:现在,当尝试在无效状态下应用操作时,光标将抛出一个错误,如下所示:
MongoError: Cursor is already initialized
Affected classes:受影响类别:AbstractCursor
FindCursor
AggregationCursor
ChangeStreamCursor
(This is the underlying cursor for(这是ChangeStream
)ChangeStream
的基础游标)ListCollectionsCursor
Cursor Stream API¶
Our Cursor types no longer extend Readable
directly. They must be transformed into a stream by calling cursor.stream()
.
const cursor = collection.find({})
const stream = cursor.stream()
stream.on("data", data=> console.log)
stream.on("error", () => client.close())
Use hasNext()
and next()
for manual iteration. Use for await of
syntax or any Promise
helpers for asynchronous iteration.
MongoClientOptions
Interface¶
With type hinting, you should find that options passed to a MongoClient
are enumerated and discoverable. We've made a large effort to process all options in the driver to give early warnings about incompatible settings to get your app up and running in a correct state quickly.
checkServerIdentity
is no longer checked before being passed to the underlying Node API. Previously, accepted values werefalse
, or a function. Now, the argument must be a function. Specifying a boolean will result in an error being thrown.- It is longer required to specify
useUnifiedTopology
oruseNewUrlParser
.
createCollection()
¶
This method no longer supports a strict
option, which returned an error if the collection did not exist. To assert the existence of a collection, use the listCollections()
method instead.
const collections = (await db.listCollections({}, { nameOnly: true })
.toArray()).map(
({name}) => name
);
if (!collections.includes(myNewCollectionName)) {
throw new Error(`${myNewCollectionName}doesn't exist`);
}
BulkWriteError
→ MongoBulkWriteError
¶
BulkWriteError
is now renamed to MongoBulkWriteError
.
When running bulk operations that make writes you can encounter errors depending on your settings. Import the new class name MongoBulkWriteError
when testing for errors in bulk operations.
DB
¶
DB
is no longer an EventEmitter
. Listen for events directly from your MongoClient
instance.
Collection.group()
¶
The Collection.group()
helper, deprecated since MongoDB 3.4, is now removed. Use the aggregation pipeline $group operator instead.
Authentication¶
gssapiServiceName
is now removed. Use authMechanismProperties.SERVICE_NAME in the URI or as an option onMongoClientOptions
.Example?authMechanismProperties.SERVICE_NAME // or new MongoClient(url, { SERVICE_NAME: "alternateServiceName" })
Specifying username and password as options is only supported in the URI or as an option on仅在URI中或MongoClientOptions
.MongoClient
上支持将用户名和密码指定为选项。Examplenew MongoClient("mongodb://username:password@<host><port>") // or new MongoClient(url, { auth: { username: "<>", password: "<>" } })
GridStore
Removal¶
The GridStore API (already deprecated in 3.x) is now replaced with GridStoreAPI(在3.x中已经弃用)现在被GridFSBucket
. GridFSBucket
取代。For more information on 有关GridFS
, see the mongodb manual.GridFS
的更多信息,请参阅mongodb手册。
Below are some snippets that represent equivalent operations.下面是一些表示等效操作的代码段。
Construction¶
// old way
const gs = new GridStore(db, filename, mode[, options])
// new way
const bucket = new GridFSBucket(client.db('test')[,options])
File Seeking¶
GridFSBucket uses the Node.js Stream API. You can replicate file seeking by using the GridFSBucket使用Node.js流API。您可以使用start
and end
options, creating a download stream from your GridFSBucket
.start
和end
选项复制文件查找,从GridFSBucket创建下载流。
bucket.openDownloadStreamByName(filename, { start: 0, end: 100 })
File Upload & Download文件上载及下载¶
await client.connect();
const filename = 'test.txt'; // whatever local file name you want您想要的任何本地文件名
const db = client.db();
const bucket = new GridFSBucket(db);
fs.createReadStream(filename)
.pipe(bucket.openUploadStream(filename))
.on('error', console.error)
.on('finish', () => {
console.log('done writing to db!');
bucket
.find()
.toArray()
.then(files => {
console.log(files);
bucket
.openDownloadStreamByName(filename)
.pipe(fs.createWriteStream('downloaded_' + filename))
.on('error', console.error)
.on('finish', () => {
console.log('done downloading!');
client.close();
});
});
});
GridFSBucket
does not need to be closed like GridStore
.
File Deletion¶
// old way
GridStore.unlink(db, name, callback);
// new way
bucket.delete(file_id);
Finding File Metadata¶
File metadata that used to be accessible on the GridStore
instance can be found by querying the bucket.
const fileMetaDataList: GridFSFile[] = bucket.find({}).toArray();
Unified Topology¶
- We internally now only manage a
unifiedTopology
when you connect to amongod
. The differences between this and previous versions is detailed here. - It is longer required to specify
useUnifiedTopology
oruseNewUrlParser
. - You must use the new
directConnection
option to connect to unitiliazed replica set members.
Explain¶
Support is now added for fine-grained verbosity modes. You can learn more about each mode here.
Command Monitoring¶
The instrument()
method is now removed. Use command monitoring instead. See our guide on command monitoring for more information.
Detailed List¶
For a detailed list of breaking changes, removals, and associated JIRA tickets, see the detailed list here.
What's New in 3.6¶
New features of the 3.6 Node.js driver release include:
- Added support for the MONGODB-AWS authentication mechanism using Amazon Web Services (AWS) Identity and Access Management (IAM) credentials
- Added support for Online Certificate Status Protocol (OCSP)
- The find() method supports
allowDiskUse()
for sorts that require too much memory to execute in RAM - The update() and replaceOne() methods support index hints
- A reduction in recovery time for topology changes and failover events
- Improvements in validation testing for the default writeConcern
- Authentication requires fewer round trips to the server, resulting in faster connection setup
- Shorter Salted Challenge Response Authentication Mechanism (SCRAM) conversations
- Ability to create collections and indexes for multiple document transactions
- Running validation for a collection in the background