Docs HomeNode.js

Usage Examples用法示例

Overview概述

Usage examples provide convenient starting points for popular MongoDB operations. 使用示例为流行的MongoDB操作提供了方便的起点。Each example provides:每个示例都提供了:

  • an explanation of the operation in the example showing the purpose and a sample use case for the method示例中的操作说明,显示了该方法的目的和示例用例
  • an explanation of how to use the operation, including parameters, return values, and common exceptions you might encounter关于如何使用该操作的说明,包括参数、返回值和可能遇到的常见异常
  • a full Node.js program that you can copy and paste to run the example in your own environment一个完整的Node.js程序,您可以复制并粘贴它以在自己的环境中运行该示例

How to Use the Usage Examples如何使用用法示例

These examples use the MongoDB Atlas sample data database. 这些示例使用MongoDB Atlas示例数据数据库。You can use this sample data on the free tier of MongoDB Atlas by following the Get Started with Atlas guide or you can import the sample dataset into a local MongoDB instance.您可以按照阿特拉斯入门指南在MongoDB Atlas的免费层上使用此示例数据,也可以将示例数据集导入本地MongoDB实例

Once you have imported the dataset, you can copy and paste a usage example into your development environment of choice. 导入数据集后,您可以将使用示例复制并粘贴到您选择的开发环境中。You can follow the quick start guide to learn more about getting started with Node.js, npm, and the Node.js driver. 您可以按照快速入门指南了解更多关于开始使用Node.js、npm和Node.js驱动程序的信息。Once you've copied a usage example, you'll have to edit one line to get the example running with your instance of MongoDB:一旦你复制了一个使用示例,你就必须编辑一行,让这个示例与你的MongoDB实例一起运行:

// Replace the following with your MongoDB deployment's connection string.将以下内容替换为MongoDB部署的连接字符串。
const uri =
"mongodb+srv://<user>:<password>@<cluster-url>?retryWrites=true&writeConcern=majority";

All examples use ES module imports. 所有示例都使用ES模块导入。You can enable ES module imports by adding the following key-value pair to your package.json file:您可以通过将以下键值对添加到您的package.json文件中来启用ES模块导入

"type": "module"
Note

CommonJS

You can use any usage example with CommonJS require. 您可以使用CommonJSrequire任何用法示例。To use CommonJS require, you must swap out the ES module import statement for your CommonJS require statement.要使用CommonJS require,您必须将ES模块import语句替换为CommonJS require语句。

Click on the tabs to see the syntax for importing the driver with ES module import and CommonJS require:单击选项卡,查看使用ES模块import和CommonJSrequire导入驱动程序的语法要求:

You can use the Atlas Connectivity Guide to enable connectivity to your instance of Atlas and find the connection string to replace the uri variable in the usage example. 您可以使用Atlas Connectivity Guide来启用与Atlas实例的连接,并在使用示例中找到用于替换uri变量的连接字符串If your instance uses SCRAM authentication, you can replace <user> with your username, <password> with your password, and <cluster-url> with the IP address or URL of your instance. 如果您的实例使用SCRAM身份验证,则可以将<user>替换为用户名,将<password>替换为密码,将<cluster-url>替换为实例的IP地址或url。Consult the Connection Guide for more information about getting connected to your MongoDB instance.有关连接到MongoDB实例的更多信息,请参阅连接指南

Available Usage Examples可用用法示例