Options
All
  • Public
  • Public/Protected
  • All
Menu

mongodb

MongoDB NodeJS Driver

The official MongoDB driver for Node.js.Node.js的官方MongoDB驱动程序。

Upgrading to version 4? Take a look at our upgrade guide here!升级到版本4?请看我们的升级指南

Quick Links快速链接

whatwhere
documentation文档 docs.mongodb.com/drivers/node
索引目录 /node-mongodb-native/4.1/modules.html
api-doc mongodb.github.io/node-mongodb-native/4.1/
npm package www.npmjs.com/package/mongodb
source github.com/mongodb/node-mongodb-native
mongodb www.mongodb.com
changelog HISTORY.md
upgrade to v4 docs/CHANGES_4.0.0.md

Bugs / Feature Requests错误/功能请求

Think you’ve found a bug? Want to see a new feature in node-mongodb-native? 你觉得你发现了一处bug了吗?要在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)和核心服务器(即服务器)项目的Bug报告都是公开的。

Support / Feedback支持/反馈

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 Log

Change history can be found in HISTORY.md.可以在history.md中找到更改历史记录。

Compatibility兼容性

For version compatibility matrices, please refer to the following links:有关版本兼容性矩阵,请参阅以下链接:

Typescript Version版本

We recommend using the latest version of typescript, however we do provide a downleveled version of the type definitions that we test compiling against typescript@4.0.2. 我们建议使用最新版本的typescript,但是我们确实提供了测试编译时使用的类型定义的降级版本typescript@4.0.2。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 please let us know and we will do our best to correct it.

Installation安装

The recommended way to get started using the Node.js 4.0 driver is by using the npm (Node Package Manager) to install the dependency in your project.开始使用Node.js 4.0驱动程序的推荐方法是使用npm(Node包管理器)在项目中安装依赖项。

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 package.json file.这将下载MongoDB驱动程序并在package.json文件中添加依赖项。

Troubleshooting故障排除

The MongoDB driver depends on several other packages. These are:MongoDB驱动程序依赖于其他几个包。这些是:

Some of these packages include native C++ extensions, consult the trouble shooting guide here if you run into issues.其中一些包包括本地C++扩展,如果遇到问题,请咨询故障解决指南

Quick Start快速启动

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.有关更深入的报道,请参阅官方文档

Create the package.json file创建package.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

Start a MongoDB Server启动MongoDB服务器

For complete MongoDB installation instructions, see the manual.有关完整的MongoDB安装说明,请参阅手册

  1. Download the right MongoDB version from MongoDBMongoDB下载正确的MongoDB版本
  2. Create a database directory (in this case under /data).创建一个数据库目录(在本例中是在/data下)。
  3. Install and start a mongod process.安装并启动mongod进程。
mongod --dbpath=/data

You should see the mongod process start up and print some status information.您应该看到mongod进程启动并打印一些状态信息。

Connect to MongoDB连接到MongoDB

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.下面的所有示例都使用异步/等待语法。

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调用都支持可选回调作为最终参数,如果提供回调,则不会返回承诺。

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.应用程序应将已成功连接到服务器的文本打印到控制台。

Insert a Document插入文档

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命令返回一个对象,其中包含有关插入操作的信息。

Find All Documents查找所有文档

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示例下面,您将看到您插入的文档。

Find Documents with a Query Filter使用查询筛选器查找文档

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匹配的文档。

Update a document更新文档

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. 该方法通过将新字段b添加到文档集1来更新字段a等于3的第一个文档。updateResult contains information about whether there was a matching document to update or not.updateResult包含有关是否存在要更新的匹配文档的信息。

Remove a document删除文档

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

Index a Collection为集合编制索引

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.有关更多详细信息,请参阅索引策略页面

Error Handling错误处理

If you need to filter certain errors from our driver we have a helpful tree of errors described in docs/errors.md.如果您需要从我们的驱动程序中过滤某些错误,我们在docs/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.messageerror.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
}

Next Steps下一步

License

Apache 2.0

© 2009-2012 Christian Amor Kvalheim © 2012-present MongoDB Contributors

Generated using TypeDoc