Docs Home / Node.js Driver

Integrate with Mongoose与Mongoose集成

Overview概述

Mongoose is a Node.js-based Object Data Modeling (ODM) library that provides schema-based data modeling, validation, query building, and business logic hooks.是一个基于Node.js的对象数据建模(ODM)库,提供基于模式的数据建模、验证、查询构建和业务逻辑挂钩。

An ODM is similar to Object Relational Mapper (ORM) used with traditional SQL databases, but designed specifically for MongoDB's document-based data model.ODM类似于用于传统SQL数据库的对象关系映射器(ORM),但专为MongoDB的基于文档的数据模型而设计。

Tip

Mongoose CompatibilityMongoose兼容性

To learn about Mongoose compatibility with different MongoDB server versions, see the Mongoose Compatibility page in the Mongoose documentation.要了解Mongoose与不同MongoDB服务器版本的兼容性,请参阅Mongoose文档中的Mongoose兼容性页面。

What is Object Data Modeling?什么是对象数据建模?

Object Data Modeling (ODM) creates a structured relationship between your application code and your database documents. With an ODM such as Mongoose, you define schemas at the application level that map to MongoDB collections and enforce structure on the documents within those collections.对象数据建模(ODM)在应用程序代码和数据库文档之间创建结构化关系。使用Mongoose等ODM,您可以在应用程序级别定义映射到MongoDB集合的模式,并在这些集合中的文档上强制执行结构。

MongoDB provides a flexible data model that allows you to modify your database schema as your application evolves. However, your use case might require consistency in your data structure across documents in a collection.MongoDB提供了一个灵活的数据模型,允许您随着应用程序的发展修改数据库模式。但是,您的用例可能需要集合中文档之间的数据结构保持一致。

Mongoose addresses this need for consistency by providing the following features:Mongoose通过提供以下功能来满足这种一致性需求:

  • Define the structure and data types for your documents定义文档的结构和数据类型
  • Generate models from schemas to interact with collections从模式生成模型以与集合交互
  • Enforce data validation rules at the application level在应用程序级别强制执行数据验证规则
  • Execute custom logic before or after database operations在数据库操作之前或之后执行自定义逻辑
  • Construct and execute database queries with a fluent API使用流畅的API构建和执行数据库查询
  • Reference documents from other collections (similar to joins)其他集合的参考文件(类似于联接)

Schema Enforcement架构强制

Mongoose enforces schemas at the application level. You define a schema that specifies the structure of documents in a collection, including field names, data types, and validation rules. Mongoose validates data against this schema before performing database operations.Mongoose在应用程序级别强制执行模式。您可以定义一个模式,指定集合中文档的结构,包括字段名、数据类型和验证规则。Mongoose在执行数据库操作之前根据此模式验证数据。

The schema and validation rules exist only in your Node.js application code. The MongoDB server itself remains unaware of these constraints and accepts any valid BSON document that your application sends.模式和验证规则仅存在于Node.js应用程序代码中。MongoDB服务器本身仍然不知道这些约束,并接受应用程序发送的任何有效的BSON文档。

Data Modeling数据建模

Mongoose requires you to define schemas and models before interacting with your collections. This structured approach might be familiar to developers with experience in relational databases or other ORMs.Mongoose要求您在与集合交互之前定义模式和模型。具有关系数据库或其他ORM经验的开发人员可能熟悉这种结构化方法。

The trade-off is reduced flexibility. When you need to modify your data structure, you must update your Mongoose schemas.代价是灵活性降低。当您需要修改数据结构时,必须更新Mongoose模式。

Schema Validation架构验证

Mongoose validates data in two ways. First, by defining field types in your schema, you specify what data types each field allows. Mongoose rejects operations that attempt to insert data that does not match the defined types.Mongoose通过两种方式验证数据。首先,通过在模式中定义字段类型,您可以指定每个字段允许的数据类型。Mongoose拒绝尝试插入与定义类型不匹配的数据的操作。

Second, you can add specific validation rules such as required fields, minimum or maximum values, string length constraints, or custom validation functions.其次,您可以添加特定的验证规则,如必填字段、最小值或最大值、字符串长度约束或自定义验证函数。

These validation rules only apply when you use Mongoose in your Node.js application. Other applications or database tools can bypass these rules because they exist only in your application code.这些验证规则仅适用于在Node.js应用程序中使用Mongoose时。其他应用程序或数据库工具可以绕过这些规则,因为它们只存在于您的应用程序代码中。

For more information on validating data by using the MongoDB Node.js driver together with MongoDB's built-in schema validation, see the MongoDB Schema Validation guide in the Server manual.有关使用MongoDB Node.js驱动程序和MongoDB内置的模式验证来验证数据的更多信息,请参阅服务器手册中的MongoDB模式验证指南。

Working with Multiple Collections使用多个集合

Both Mongoose and the MongoDB Node.js driver support combining documents from multiple collections, similar to joins in relational databases.Mongoose和MongoDB Node.js驱动程序都支持组合来自多个集合的文档,类似于关系数据库中的连接。

Populate in Mongoose在Mongoose流行

Mongoose provides the populate() method to reference documents from other collections. You define references in your schema by specifying which collection they reference. Mongoose提供populate()方法来引用其他集合中的文档。通过指定引用的集合,可以在架构中定义引用。ObjectId is a common type to use for references, but Mongoose also supports the use of other types such as strings, numbers, UUIDs, and buffers. When querying, Mongoose can automatically replace these references with the actual documents.ObjectId是用于引用的常见类型,但Mongoose也支持使用其他类型,如字符串、数字、UUID和缓冲区。查询时,Mongoose可以自动用实际文档替换这些引用。

Mongoose performs populate operations by executing multiple queries. This approach can be beneficial in certain scenarios, such as when working with large scans or when indexes are missing.Mongoose通过执行多个查询来执行填充操作。这种方法在某些情况下可能是有益的,例如在处理大型扫描或缺少索引时。

$lookup in MongoDBMongoDB中的$lookup

MongoDB provides the $lookup aggregation stage for performing an action similar to left outer joins between collections in the same database. The MongoDB Node.js driver gives you direct access to this feature through aggregation pipelines.MongoDB提供了$lookup聚合阶段,用于在同一数据库中的集合之间执行类似于左外连接的操作。MongoDB Node.js驱动程序允许您通过聚合管道直接访问此功能。

The $lookup operator runs as a single aggregation pipeline operation. This approach can offer performance benefits in some cases, but the actual performance depends on factors such as your data size, available indexes, and query patterns.$lookup运算符作为单个聚合管道操作运行。在某些情况下,这种方法可以提供性能优势,但实际性能取决于数据大小、可用索引和查询模式等因素。

Get Started with Mongoose开始使用Mongoose

To learn how to install Mongoose, connect to MongoDB, and perform CRUD operations by using Mongoose schemas and models, see the Mongoose Get Started tutorial.要了解如何安装Mongoose、连接到MongoDB以及使用Mongoose模式和模型执行CRUD操作,请参阅Mongoose入门教程

Additional Resources其他资源