The official MongoDB driver for Node.js.Node.js的官方MongoDB驱动程序。
Upgrading to version 4? 升级到版本4?Take a look at our upgrade guide here!在这里查看升级指南!
what | where |
---|---|
docs.mongodb.com/drivers/node | |
api-doc | mongodb.github.io/node-mongodb-native/ |
npm package | www.npmjs.com/package/mongodb |
source | github.com/mongodb/node-mongodb-native |
mongodb | www.mongodb.com |
changelog | HISTORY.md |
upgrade to v4 | etc/notes/CHANGES_4.0.0.md |
contributing | CONTRIBUTING.md |
Think you’ve found a bug? 你认为你发现了一个bug?Want to see a new feature in 想在node-mongodb-native
? node-mongodb-native
中看到新功能吗?Please open a case in our issue management tool, JIRA:请在问题管理工具JIRA中打开案例:
Bug reports in JIRA for all driver projects (i.e. NODE, PYTHON, CSHARP, JAVA) and the Core Server (i.e. SERVER) project are public.JIRA中所有驱动程序项目(即NODE、PYTHON、CSHARP、JAVA)和核心服务器(即Server)项目的错误报告都是公开的。
For issues with, questions about, or feedback for the Node.js driver, please look into our support channels. 有关Node.js驱动程序的问题、问题或反馈,请查看支持渠道。Please do not email any of the driver developers directly with issues or questions - you're more likely to get an answer on the MongoDB Community Forums.请不要直接向任何驱动程序开发人员发送问题电子邮件,您更有可能在MongoDB社区论坛上得到答案。
Change history can be found in 可以在HISTORY.md
.HISTORY.md
中找到更改历史记录。
For version compatibility matrices, please refer to the following links:有关版本兼容性矩阵,请参阅以下链接:
We recommend using the latest version of typescript, however we currently ensure the driver's public types compile against 我们建议使用最新版本的typescript,但是我们目前确保驱动程序的公共类型可以根据typescript@4.1.6
. typescript@4.1.6
。This is the lowest typescript version guaranteed to work with our driver: older versions may or may not work - use at your own risk. 这是保证与驱动程序一起使用的最低typescript版本:较旧的版本可能工作,也可能不工作-使用风险自负。Since typescript does not restrict breaking changes to major versions we consider this support best effort. 由于typescript不限制对主要版本的破坏性更改,我们认为这是最好的支持。If you run into any unexpected compiler failures against our supported TypeScript versions please let us know by filing an issue on our JIRA.如果您在我们支持的TypeScript版本中遇到任何意外的编译器故障,请通过在JIRA上提交问题告知我们。
The recommended way to get started using the Node.js 4.x driver is by using the 开始使用Node.js 4x驱动程序的推荐方法是使用npm
(Node Package Manager) to install the dependency in your project.npm
(Node Package Manager)在项目中安装依赖项。
After you've created your own project using 使用npm init
, you can run:npm init
创建自己的项目后,可以运行:
npm install mongodb
# or ...
yarn add mongodb
This will download the MongoDB driver and add a dependency entry in your 这将下载MongoDB驱动程序,并在package.json
file.package.json
文件中添加一个依赖项。
If you are a Typescript user, you will need the Node.js type definitions to use the driver's definitions:如果您是Typescript用户,则需要Node.js类型定义才能使用驱动程序的定义:
npm install -D @types/node
The MongoDB driver depends on several other packages. These are:MongoDB驱动程序依赖于其他几个包。这些是:
Some of these packages include native C++ extensions. 其中一些包包括本机C++扩展。Consult the trouble shooting guide here if you run into issues.如果遇到问题,请参阅此处的故障排除指南。
This guide will show you how to set up a simple application using Node.js and MongoDB. 本指南将向您展示如何使用Node.js和MongoDB设置一个简单的应用程序。Its scope is only how to set up the driver and perform the simple CRUD operations. 它的范围只是如何设置驱动程序和执行简单的CRUD操作。For more in-depth coverage, see the official documentation.有关更深入的报道,请参阅官方文档。
package.json
filepackage.json
文件First, create a directory where your application will live.首先,创建应用程序所在的目录。
mkdir myProject
cd myProject
Enter the following command and answer the questions to create the initial structure for your new project:输入以下命令并回答问题以创建新项目的初始结构:
npm init -y
Next, install the driver as a dependency.接下来,将驱动程序作为依赖项安装。
npm install mongodb
For complete MongoDB installation instructions, see the manual.有关完整的MongoDB安装说明,请参阅手册。
/data
下)。mongod
process.mongod
进程。mongod --dbpath=/data
You should see the mongod process start up and print some status information.您应该看到mongod
进程启动并打印一些状态信息。
Create a new app.js file and add the following code to try out some basic CRUD operations using the MongoDB driver.创建一个新的app.js
文件并添加以下代码,以使用MongoDB驱动程序尝试一些基本的CRUD操作。
Add code to connect to the server and the database myProject:添加连接到服务器和数据库myProject
的代码:
NOTE:
All the examples below use async/await syntax.下面的所有示例都使用async/await语法。
However, all async API calls support an optional callback as the final argument, if a callback is provided a Promise will not be returned.然而,所有异步API调用都支持可选的回调作为最终参数,如果提供了回调,则不会返回Promise。
const { MongoClient } = require('mongodb');
// or as an es module:
// import { MongoClient } from 'mongodb'
// Connection URL
const url = 'mongodb://localhost:27017';
const client = new MongoClient(url);
// Database Name
const dbName = 'myProject';
async function main() {
// Use connect method to connect to the server
await client.connect();
console.log('Connected successfully to server');
const db = client.db(dbName);
const collection = db.collection('documents');
// the following code examples can be pasted here...
return 'done.';
}
main()
.then(console.log)
.catch(console.error)
.finally(() => client.close());
Run your app from the command line with:使用以下命令从命令行运行应用程序:
node app.js
The application should print Connected successfully to server to the console.应用程序应将“已成功连接到服务器”打印到控制台。
Add to app.js the following function which uses the insertMany method to add three documents to the documents collection.向app.js
添加以下函数,该函数使用insertMany
方法将三个文档添加到documents
集合中。
const insertResult = await collection.insertMany([{ a: 1 }, { a: 2 }, { a: 3 }]);
console.log('Inserted documents =>', insertResult);
The insertMany command returns an object with information about the insert operations.insertMany
命令返回一个包含有关插入操作信息的对象。
Add a query that returns all the documents.添加返回所有文档的查询。
const findResult = await collection.find({}).toArray();
console.log('Found documents =>', findResult);
This query returns all the documents in the documents collection. 此查询返回documents
集合中的所有文档。If you add this below the insertMany example you'll see the document's you've inserted.如果将此添加到insertMany示例下面,您将看到您插入的文档。
Add a query filter to find only documents which meet the query criteria.添加查询筛选器以仅查找符合查询条件的文档。
const filteredDocs = await collection.find({ a: 3 }).toArray();
console.log('Found documents filtered by { a: 3 } =>', filteredDocs);
Only the documents which match 只应返回与'a' : 3
should be returned.'a' : 3
匹配的文档。
The following operation updates a document in the documents collection.以下操作将更新documents
集合中的文档。
const updateResult = await collection.updateOne({ a: 3 }, { $set: { b: 1 } });
console.log('Updated documents =>', updateResult);
The method updates the first document where the field a is equal to 3 by adding a new field b to the document set to 1. 该方法通过向设置为1
的文档添加新字段b
来更新字段a
等于3
的第一个文档。updateResult
contains information about whether there was a matching document to update or not.包含有关是否存在要更新的匹配文档的信息。
Remove the document where the field a is equal to 3.删除字段a
等于3
的文档。
const deleteResult = await collection.deleteMany({ a: 3 });
console.log('Deleted documents =>', deleteResult);
Indexes can improve your application's performance. 索引可以提高应用程序的性能。The following function creates an index on the a field in the documents collection.以下函数在documents
集合中的a
字段上创建索引。
const indexName = await collection.createIndex({ a: 1 });
console.log('index name =', indexName);
For more detailed information, see the indexing strategies page.有关详细信息,请参阅索引策略页面。
If you need to filter certain errors from our driver we have a helpful tree of errors described in etc/notes/errors.md.如果您需要从驱动程序中筛选某些错误,我们有一个有用的错误树,如etc/notes/errors.md所述。
It is our recommendation to use 我们建议对错误使用instanceof
checks on errors and to avoid relying on parsing error.message
and error.name
strings in your code. instanceof
检查,并避免在代码中解析error.message
和error.name
字符串。We guarantee 我们保证instanceof
checks will pass according to semver guidelines, but errors may be sub-classed or their messages may change at any time, even patch releases, as we see fit to increase the helpfulness of the errors.instanceof
检查将根据semver指南通过,但错误可能会被细分,或者其消息可能随时更改,即使是补丁版本,因为我们认为可以增加错误的有用性。
Any new errors we add to the driver will directly extend an existing error class and no existing error will be moved to a different parent class outside of a major release. 我们添加到驱动程序中的任何新错误都将直接扩展现有错误类,并且不会将任何现有错误移动到主要版本之外的其他父类。This means 这意味着instanceof
will always be able to accurately capture the errors that our driver throws (or returns in a callback).instanceof
将始终能够准确地捕获驱动程序抛出(或在回调中返回)的错误。
const client = new MongoClient(url);
await client.connect();
const collection = client.db().collection('collection');
try {
await collection.insertOne({ _id: 1 });
await collection.insertOne({ _id: 1 }); // duplicate key error
} catch (error) {
if (error instanceof MongoServerError) {
console.log(`Error worth logging: ${error}`); // special case for some reason
}
throw error; // still want to crash
}
© 2009-2012 Christian Amor Kvalheim © 2012-present MongoDB Contributors
Generated using TypeDoc