Mongoose相关问题

汇总常见技术疑问、解决思路和实践经验。

问题答案 12026年5月27日 01:20

Nestjs : How to use mongoose to start a session for transaction?

Install and Configure the Mongoose Module:First, install the required packages: and . This can be accomplished by executing the following command:Next, import into your NestJS module using or to establish a connection to the MongoDB database.Create a Schema:Define a Mongoose schema to enable NestJS to interact with specific MongoDB collections.Inject the Model into the Service:In your service file, inject the corresponding model via the constructor.Start the Transaction Session:In the service, access the database connection using the property of the injected model and start a new transaction session with . Then, use this session to execute transactional operations.Here is a simplified example demonstrating how to start and use a Mongoose transaction in a NestJS service:This is the basic workflow for implementing transaction operations with Mongoose in NestJS. In actual applications, you must implement database operations based on your specific business logic and handle more complex error scenarios.
问题答案 12026年5月27日 01:20

How to do raw mongodb operations in mongoose?

In Mongoose, while the library provides many convenient methods for interacting with MongoDB, there are times when you might need to perform native MongoDB operations. Mongoose offers several approaches to directly utilize native MongoDB operations.1. Using the MethodThe method allows you to access the native MongoDB collection object, enabling you to directly use native MongoDB methods. For example:2. Using the MethodAlthough Mongoose has its own method, you can also use the native aggregation framework. The following example demonstrates how to perform native aggregation operations:3. Using the ObjectYou can also access the underlying MongoDB database object through Mongoose's object to perform more complex operations, such as transaction handling:Although Mongoose provides many high-level abstractions that simplify interaction with MongoDB, when performing complex or specific database operations, directly using native MongoDB operations is entirely feasible. These methods can help you maintain the convenience of Mongoose while flexibly leveraging MongoDB's powerful features, which is particularly useful for handling complex queries or performance optimization.
问题答案 12026年5月27日 01:20

How do I include a virtual field in API response using Mongoose?

When using Mongoose for MongoDB data modeling, virtual fields are a very useful feature that allows you to define fields not directly stored in the database documents. Virtual fields are typically used to generate new fields based on existing database fields. For example, you can use a virtual field to combine a person's first and last name without storing the combined field in the database.To define virtual fields in a Mongoose model, you can use the method of the model. Here is an example of how to define virtual fields in a Mongoose model:In the above code, we create a user model with and fields, and define a virtual field that returns the combination of the first and last name.However, by default, when querying data from Mongoose and converting it to JSON format, virtual fields are not included. To include virtual fields in API responses, you need to set in the schema options to ensure virtual fields are included in the response:Now, when you send user data as a response using , the virtual field will be included. For example:In this example, when you request specific user information (using their ID), the user object retrieved via automatically applies the method, which includes the virtual field, and then sends it back to the client via .In summary, to include virtual fields in API responses, you need to correctly define virtual fields in your model and set or to ensure these fields are serialized. This way, whenever data is converted to JSON, virtual fields will be automatically included.
问题答案 12026年5月27日 01:20

How to build a conditional query in Mongoose?

Building conditional queries in Mongoose typically involves using methods such as , , or along with query objects. Here are the detailed steps and examples:Step 1: Connecting to the MongoDB DatabaseFirst, ensure you have connected to the MongoDB database.Step 2: Defining the ModelDefine a Mongoose model that maps to a collection in the database.Step 3: Building Conditional QueriesExample 1: Find all users named 'John'Example 2: Find all users older than 20Example 3: Find users with status 'active' and age greater than 20Example 4: Use to find a specific userStep 4: Using Chained Queries (Optional)Mongoose also supports chained queries, making it more intuitive to build complex queries.These steps demonstrate how to build and execute conditional queries in Mongoose. This approach enables flexible database querying to meet various business requirements.
问题答案 12026年5月27日 01:20

How to implement pagination and total with mongoose

When working with Mongoose (a MongoDB object modeling tool) for data operations, implementing pagination and aggregation is a common requirement. Below are the specific steps and code examples for implementing these features in Mongoose.Pagination Implementation:Pagination is primarily used to improve efficiency when handling large datasets and enhance user experience. In Mongoose, we can implement pagination using the and methods.Example Code:Assume we have a model called , and we want to retrieve data for the -th page, displaying items per page.Here, skips all data from previous pages, and restricts the number of returned items, implementing pagination.Aggregation:When handling statistics or reports, we often need to perform aggregations. Mongoose can implement complex aggregations using the method.Example Code:Assume we want to calculate the total price of all products; we can use the following code:In this example, the operator is used to merge all documents into a single document and uses to calculate the total of the field.Summary:Through these two examples, we can see that using Mongoose for pagination and aggregation is straightforward and efficient. These operations are particularly valuable when handling large-scale data and report generation, enhancing application performance and user experience. Of course, specific implementations may require appropriate adjustments based on the data model and specific requirements.
问题答案 12026年5月27日 01:20

JavaScript NoSQL Injection prevention in MongoDB

The key to preventing JavaScript NoSQL injection in MongoDB is ensuring that applications do not directly incorporate untrusted data into query execution. The following are effective protective measures:1. Using Secure Database OperationsThe most critical protective measure is to ensure the use of parameterized queries or MongoDB's secure APIs. This prevents the direct incorporation of user input into queries, thereby mitigating injection risks.For example, when using the MongoDB Node.js driver, avoid dynamically constructing queries via string concatenation and instead use parameterized methods:In the second example, we mitigate injection risks by passing the username as a parameter to the query.2. Validating and Sanitizing InputIt is essential to validate and sanitize input data before processing user input. Libraries like or can be used to ensure input adheres to expected formats and eliminate special characters that might cause injection.For example:3. Using ORM or ODMUtilizing Object-Relational Mapping (ORM) or Object-Document Mapping (ODM) libraries, such as Mongoose (an ODM for MongoDB), can help automatically address numerous security concerns. These libraries typically incorporate built-in mechanisms to prevent injection.For example, in Mongoose, all queries are constructed through the ODM, reducing the risk of direct injection:4. Using Latest Security Practices and LibrariesMaintaining up-to-date libraries and frameworks is vital for security. Developers should routinely update their dependencies and monitor security updates and patches. This helps mitigate risks from emerging security threats and vulnerabilities.SummaryPreventing JavaScript NoSQL injection in MongoDB is primarily accomplished by ensuring all user input is appropriately processed and validated, alongside the adoption of secure programming practices. These measures substantially reduce security risks arising from insecure data handling.
问题答案 12026年5月27日 01:20

How to update a object in mongodb via mongoose?

In Mongoose, updating objects in a MongoDB database can be achieved through various methods, including , , , and . Here are some examples of using these methods:UsingThe method updates a single document; it matches the first document that satisfies the query condition and updates only the first found document.UsingIf you want to update multiple documents, you can use the method. It applies the update operation to all documents that match the query.UsingThe method finds the first document that matches the query, updates it, and returns the document before or after the update (depending on options).In the above code, is one of MongoDB's update operators used to increment or decrement the value of existing fields.UsingIf you have the document's ID, you can use the method to update this specific document.During development, ensure to consider error handling, data validation, and performance impact when performing update operations. Additionally, Mongoose's update operations do not run validators by default; if you need to run validators, set in the options.
问题答案 12026年5月27日 01:20

How do I perform a query in Mongoose?

When working with Mongoose and MongoDB, executing queries is a core and essential functionality. Mongoose offers multiple methods for querying data from the database, which can handle both simple and complex query requirements. Below, I will detail several common query methods with corresponding examples.1. Using the MethodThe method is one of the most commonly used query methods, which can be used to retrieve multiple documents matching specified criteria.Example Code:In this example, we query all users named "Zhang San". The first parameter of the method is the query condition, and the second parameter is a callback function to handle query results or errors.2. Using the MethodIf you need to find a single document matching the criteria, use the method.Example Code:This method is similar to , but it returns only the first matching document.3. Using the MethodIf you know the document ID, use the more direct method.Example Code:Here, we retrieve a user by document ID.4. Advanced Usage of Query ConditionsMongoose supports complex query conditions, such as using operators like (greater than) and (less than).Example Code:In this example, we query all users with an age greater than 18.5. Chained QueriesMongoose allows building queries through chained calls, making the syntax more flexible and powerful.Example Code:In this example, we chain multiple methods to construct complex query conditions and result selection.Through these methods, you can choose appropriate query methods and strategies based on specific requirements. Mongoose's robustness and flexibility ensure efficient and effective data retrieval from MongoDB.
问题答案 12026年5月27日 01:20

Why mongoose findOne always returns null

The method returns in the following scenarios:1. Query conditions do not matchThe method returns when no documents match the query conditions in the database. For example:In this example, if no user with the username 'nonexistentuser' exists in the database, the query result will return .2. Incorrect model name or collection nameUsing an incorrect model name or collection name during model definition or query execution can result in . For example:Here, the incorrect model name 'WrongModelName' is used, so even if matching documents exist, the query returns .3. Connection issuesIf Mongoose fails to connect to the MongoDB server or the connection is interrupted before the query, the query may fail and return . Verifying connection status is recommended:4. Asynchronous processing errorsWhen handling database operations with asynchronous logic, improper handling of the asynchronous flow may cause the query to complete before data is returned, resulting in . Ensure correct implementation of asynchronous patterns like Promises or async/await:5. SolutionsTo resolve these issues, ensure query conditions are correct, verify model and collection names, check database connection status, and properly handle asynchronous code.
问题答案 12026年5月27日 01:20

How to save array of objects in mongoose

In Mongoose, saving object arrays typically involves the following steps:1. Define SchemaFirst, define a Mongoose Schema to map to MongoDB documents. If the array you're storing contains objects, define these objects as subdocuments within the Schema.Here's an example: Suppose we want to save a user with multiple addresses, each address being an object containing street, city, and zip code:2. Create and Save DocumentsAfter defining the Schema, create a new instance of the Mongoose model and populate the array with objects. Then, save the document to MongoDB using .3. Update Arrays in DocumentsTo add more addresses or modify existing ones in an existing document, use to add new addresses or directly modify the array elements and save.4. Use Mongoose's Advanced FeaturesMongoose offers methods for handling arrays easily, including MongoDB operators like and , which can be used directly in update operations to efficiently modify arrays.By following these steps, you can effectively manage and operate on arrays containing objects in Mongoose. This is very useful for handling data with complex structures.
问题答案 12026年5月27日 01:20

How to set _id to db document in Mongoose?

By default, each document in a Mongoose model has an field, which is typically automatically generated as a MongoDB ObjectId. A MongoDB ObjectId is a 12-byte field that typically contains a timestamp, a random value, and an increment counter to ensure the uniqueness of each .However, there may be specific requirements where you need to set to a specific value or use different data types (such as strings or numbers). In Mongoose, you can customize the type and value of when defining the Schema.Here is an example of how to customize in Mongoose:In this example, we define a model with explicitly set to String type. When creating the instance, we manually specify as . This ensures that MongoDB uses the custom ID instead of generating a default ObjectId.This approach allows you to customize the ID based on business needs, such as using a user's email address or other business identifiers as the document's unique identifier. However, when manually setting , you must ensure its uniqueness to avoid errors from duplicate values.
问题答案 12026年5月27日 01:20

How is order of properties maintained for sort in mongodb?

Maintaining the order of sorted attributes in MongoDB can primarily be achieved through the following methods:1. Using IndexesIn MongoDB, we can create an index on a specific field within a collection to optimize sorting operations. For example, if we frequently sort by dates or specific fields, creating an index can enhance these operations.Example:2. Maintaining Order During Write OperationsWhen data order has specific application-layer logic—such as in a to-do list application where entries must be ordered by insertion time—we can include an field in each document. Increment this field based on the value of the last document when inserting new entries.Example:Then, query using the field for sorting:3. Using Aggregation FrameworkMongoDB's aggregation framework offers robust data processing capabilities, allowing us to sort data using the pipeline within aggregation queries.Example:4. Updating Order MaintenanceIn scenarios requiring dynamic order adjustments during updates—such as in a leaderboard application where user scores change—we must update scores while maintaining order. After an update operation, perform a sort to ensure correct ordering.Example:By employing these methods, we can effectively maintain and manage the sorted order of attributes in MongoDB.
问题答案 42026年5月27日 01:20

How to references with a one to many relationship in mongoose?

In Mongoose, implementing a one-to-many relationship typically involves two models: the parent model (e.g., 'User') and the child model (e.g., 'Comment'), where the parent model references multiple instances of the child model. Below is how to implement such a one-to-many relationship in Mongoose:First, define the child model's schema, for example, the Comment model:Next, define the parent model's schema and use an array field to reference the child model's ObjectIds. The keyword in Mongoose specifies the name of the referenced model:In this example, each user can have multiple comments, and the field in the user model is an array storing ObjectIds that reference the model documents.When querying a user and their related comments, you can use the function to automatically replace these ObjectIds with the corresponding comment documents:In practical applications, you can further specify the required fields for the function or sort and filter the results.This referencing relationship is flexible as you can independently add or remove comments without modifying the user document. Furthermore, it is straightforward to query all comments associated with a specific user. However, it is important to note that if the 'many' side of a one-to-many relationship contains a very large number of items, you may need to consider pagination or limiting the number of references to avoid performance issues.
问题答案 12026年5月27日 01:20

How to achieve rollback in transactions in mongoDB?

In MongoDB, transactions are typically used in environments supporting multi-document ACID transactions, such as MongoDB 4.0 and above in replica sets or MongoDB 4.2 and above in sharded clusters. Transactions help ensure data consistency and integrity. MongoDB supports transaction rollback to handle errors or exceptions that occur during transaction execution.Steps to Implement Transaction RollbackStart Transaction:Use MongoDB's client session () to initiate a new session and employ to begin a transaction.Execute Operations:Perform the required database operations within the transaction context. These operations must utilize the same session instance to guarantee execution within the transaction scope.Commit or Rollback Transaction:Decide to commit or rollback the transaction based on operation outcomes. Commit if all operations succeed; rollback if any operation fails to maintain data consistency.Example ScenarioSuppose you are managing a database for an e-commerce platform. You need to update inventory information and record transaction logs. First, attempt to insert new inventory entries and log entries within a transaction. If an error occurs during insertion (e.g., network issues or data conflicts), roll back these changes to prevent data inconsistency.By following these steps, MongoDB enables developers to leverage transactions in database operations for maintaining data integrity and consistency. Transaction rollback is a critical mechanism to restore consistency when issues arise.
问题答案 12026年5月27日 01:20

How to get number of documents using Mongoose?

In Mongoose, the standard method for retrieving document counts is to use the method. This approach is straightforward and allows you to count the number of documents in the database that meet specific criteria.Here is an example demonstrating how to use on a model named :In the above example, accepts two parameters. The first specifies the query condition (if omitted, it counts all documents in the collection), and the second is a callback function invoked upon completion. This callback receives two arguments: and . If successful, is and holds the document count.Note that for counting all documents without query conditions, you can pass the callback function as the first argument.If you are using , you can do the following:In this example, returns a Promise, enabling cleaner asynchronous handling with .To summarize, is the recommended method in Mongoose for obtaining document counts, allowing you to specify query conditions to count documents matching specific criteria.
问题答案 12026年5月27日 01:20

How can I do type checking in MongoDB?

Performing type checking in MongoDB is an important operation that ensures data consistency and accuracy. MongoDB is a document-based NoSQL database that stores data in BSON format (similar to JSON). BSON supports rich data types such as strings, integers, and dates. Type checking in MongoDB typically involves the following methods:1. Using the Operator for QueriesMongoDB provides the operator to query field types. For example, to find all documents where the field is of integer type, you can use the following query:Additionally, can accept multiple types, which is useful when the field may store values of various types:2. Performing Type Validation During Data Insertion or UpdatePerforming type validation at the application layer is a common practice. Before writing data to MongoDB, you can check data types in your application code to ensure they meet expectations. For example, using JavaScript:3. Using MongoDB Schema ValidationStarting from MongoDB 3.6, MongoDB introduced Schema Validation. With this feature, you can set data validation rules for collections to ensure data types and formats meet expectations. For example, the following rule ensures that the field must be an integer:Application Scenario ExampleSuppose you work on an e-commerce platform and need to store user information. The field in user information must be an integer. You can use the third method (Schema Validation) described above to ensure that the field is always an integer when inserting data. This prevents data anomalies caused by type errors.In summary, type checking in MongoDB can be achieved through query operators, application-layer code checks, and using Schema Validation. These methods help developers ensure data type safety and consistency in the database.
问题答案 12026年5月27日 01:20

Why mongodb output _id instead of id?

Given you're using Mongoose, you can use 'virtuals', which are essentially fake fields that Mongoose creates. They're not stored in the DB, they just get populated at run time:Any time is called on the Model you create from this Schema, it will include an field that matches the field Mongo generates. Likewise, you can set the behavior for in the same way.See:http://mongoosejs.com/docs/api.htmlhttp://mongoosejs.com/docs/guide.html#toJSONhttp://mongoosejs.com/docs/guide.html#toObjectYou can abstract this into a BaseSchema for all your models, then extend/invoke to keep the logic in one place. I wrote the above while creating an Ember/Node/Mongoose app, since Ember really prefers to have an field to work with.As of Mongoose v4.0, part of this functionality is supported out of the box. It's no longer required to manually add a virtual field as explained by @Pascal Zajac. Mongoose assigns each of your schemas an virtual getter by default, which returns the document's field cast to a string, or in the case of ObjectIds, its hexString. If you don't want an getter added to your schema, you may disable it by passing this option at schema construction time. Source However, to export this field to JSON, it's still required to enable serialization of virtual fields: I used this: I think it would be great if they automatically suppress when is true. I create a method on my models where I do this. It's also a good place to rename/remove other attributes you don't want to send to the client: Here is an alternative version of the answer provided by @user3087827. If you find that is undefined, then you can use: MongoDB uses as the default field to store the unique identifier of documents (primary key). There are several reasons behind this decision: Uniqueness: MongoDB designs the field to ensure that each document in a collection can be uniquely identified. MongoDB automatically generates an ObjectId type value for each new document, which is globally unique—meaning that two documents will not have the same even across different servers or clusters. Consistency: Using as the standard field name for all documents provides a consistent interface for developers to reference the primary key. This consistency simplifies data model design and allows developers to write more generic code for handling different documents. Indexing: In MongoDB, each collection automatically creates a unique index on the field. This design ensures fast lookup and efficient data integrity checks. Without this default index, developers would need to manually create indexes for their chosen primary key fields, increasing development complexity. For example, consider a user collection (collection) containing many user documents (document). Each document will automatically have an field, as follows: Even if developers choose to use a custom field (such as ) as the document identifier, it is generally recommended to use the default field to maintain consistency and leverage MongoDB's built-in indexing. In cases where specific needs arise, developers can map to or any other field they prefer at the application layer. In such cases, developers are responsible for maintaining the uniqueness and indexing of the additional fields.
问题答案 12026年5月27日 01:20

How to achieve oop in nodejs

In Node.js, the primary approach to implementing Object-Oriented Programming (OOP) is through JavaScript's class and prototype inheritance features. Here are several steps to implement OOP:1. Defining ClassesWith ES6, the introduction of the keyword provides a more intuitive way to define classes. Classes serve as blueprints for objects, allowing the definition of properties and methods.2. Creating Object InstancesUse the keyword to instantiate objects from a class.3. InheritanceA class can inherit properties and methods from another class using the keyword.4. EncapsulationEncapsulation is a core concept in OOP, meaning that the state and behavior of an object are contained internally, exposing only limited interfaces for external interaction.In this example, is a private property that cannot be accessed directly from outside the class; it can only be manipulated through the class's methods.5. PolymorphismPolymorphism means that subclasses can define a method with the same name as in the parent class but with different behavior.In this example, the class overrides the method of the class, demonstrating polymorphism.By following these steps, we can implement the fundamental concepts of OOP in Node.js, including class definition, inheritance, encapsulation, and polymorphism. These principles help organize and modularize code, making it easier to understand and maintain.
问题答案 12026年5月27日 01:20

How to set objectid as a data type in mongoose

Why Setting ObjectId is Crucial for Mongoose ApplicationsObjectId is not only the default ID type in MongoDB but also an inherent feature of Mongoose. When not explicitly set, Mongoose automatically infers the field as ObjectId, but explicit configuration brings multiple benefits:Type safety: Avoid query failures due to implicit inference (e.g., treating strings as ObjectId). The Mongoose documentation explicitly states that explicitly specifying the type reduces runtime errors.Performance optimization: ObjectId supports efficient binary storage and indexing operations, improving query speed (real-world tests show it is 30% faster than string IDs).Data integrity: Enforces the presence of the field, preventing missing critical identifiers during document creation. Key tip: In Mongoose, the field defaults to ObjectId type, but explicit setting covers special cases (e.g., custom ID generation logic) and ensures consistency with the database layer. Detailed Methods for Setting ObjectId in Schema Mongoose provides as the standard way to define ObjectId fields. Here are the core configuration steps and code examples: Basic Configuration: Explicitly Declare ObjectId Type In the schema, use to explicitly specify the field type. Typically, the field should be set as required () since this is MongoDB's default behavior. Key points explained: The field is Mongoose's implicit primary key; explicit setting covers all scenarios (e.g., custom IDs). Omitting allows Mongoose to auto-generate ObjectId, but explicit setting ensures type safety. is mandatory since MongoDB requires a unique for every document. Advanced Usage: Handling Nested ObjectId References ObjectId is commonly used to reference other collections. Use the option to simplify queries: Practical recommendations: Always use for nested references to avoid manual ID conversion errors. Avoid passing ObjectId strings from the frontend; use Mongoose's method for conversion. Common Issues and Solutions Issue 1: Query Failures Due to Type Inference Errors Cause: Not explicitly setting causes Mongoose to infer the field as a string or other type. Solution: Explicitly specify the type in the schema. For example: Validation tool: Use to check ID validity: Issue 2: Custom ObjectId Generation Logic Scenario: Need to use UUID or custom IDs (e.g., business rule-based generation). Solution: Use a function to customize generation: Note: Custom IDs must ensure uniqueness to avoid database conflicts. Mongoose documentation recommends: For non-_id fields, prefer type to avoid type errors. Review Mongoose's class documentation: Official Reference Issue 3: Handling ObjectId in Nested Documents Problem: Storing ObjectId references in array fields may prevent Mongoose from auto-indexing. Solution: Use and options: Performance tip: Adding an index to ObjectId fields accelerates queries (e.g., ). Conclusion Correctly setting ObjectId data type in Mongoose is a critical step for building reliable MongoDB applications. By explicitly defining types, handling nested references, and avoiding common pitfalls, developers ensure data consistency, enhance query performance, and reduce runtime issues. Key recommendations include: Always explicitly set: In the schema, define even when using the default . Follow best practices: Consult Mongoose's official documentation (Schema Types Guide) and conduct performance testing. Avoid common traps: Never confuse ObjectId strings with object instances; use for frontend conversion. While ObjectId configuration in Mongoose appears straightforward, it directly impacts application robustness. For complex scenarios, explore Mongoose's ObjectId type documentation or seek solutions via GitHub Issues. Properly setting ObjectId not only optimizes data storage but also lays the foundation for future aggregation queries and relational operations—essential knowledge for Node.js developers.
问题答案 12026年5月27日 01:20

Mongoose : what's the differences between Model.create and Collection.insert

在Mongoose中, 方法与直接在 MongoDB 的 上执行插入操作有一些关键区别。下面我将详细解释这两者之间的主要差异,并通过一些实际应用场景来举例说明。1. 数据验证Model.create():当使用 Mongoose 的 方法时,它会自动执行定义在模型上的验证规则。这是一个非常重要的特性,因为它保证了插入到数据库中的数据符合我们预设的格式和规范。例如,如果我们有一个用户模型,其中定义了邮箱字段必须符合电子邮件的格式,使用 方法插入数据时,如果邮箱字段不符合格式,Mongoose 将会抛出错误。Collection 插入:直接使用 MongoDB 的 collection 插入数据(如 或 )时,并不会执行 Mongoose 层面上定义的验证规则。这意味着,即使数据不符合模型的验证规则,它们也可以被插入到数据库中,这可能会导致数据的不一致性。2. Mongoose中间件的触发Model.create():在 Mongoose 中,可以定义中间件(pre 和 post hooks),这些中间件可以在执行数据库操作之前或之后运行。使用 方法时,这些中间件会被触发。例如,你可以在保存文档之前自动加密用户的密码。Collection 插入:直接使用 MongoDB 的 collection 方法插入文档时,Mongoose 定义的中间件不会被触发。这意味着某些预处理或后处理逻辑需要在应用层手动处理。3. 返回的对象类型Model.create():这个方法返回的是 Mongoose 的文档实例。这些实例包含了模型的方法和属性,使得对数据进一步处理变得更加方便。Collection 插入:直接使用 MongoDB 的 collection 方法插入数据时,返回的是原生的 MongoDB 输出,通常包括状态信息,如插入的文档数,而不包括 Mongoose 模型的方法和属性。总结总的来说,虽然直接使用 MongoDB 的 collection 方法插入数据在某些情况下看起来更为直接和快捷,但 方法提供了数据验证、触发中间件、返回 Mongoose 文档实例等强大功能,这有助于保持应用数据的一致性和安全性,同时简化了数据操作逻辑。这些特性在构建复杂的商业应用时尤其重要。