VOOZH about

URL: https://www.geeksforgeeks.org/mongodb/mongoose-document-model-api/

⇱ Mongoose Document Model() API - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

Mongoose Document Model() API

Last Updated : 28 Apr, 2025

The Mongoose Document APIModel() method of the Mongoose API is used on the Document model. It allows to create a MongoDB class. Using this method we can create model that can interact with MongoDB for all operations. Let us understand the APIModel() method using an example.

Syntax:

mongoose.model( doc, fields, skipId );

Parameters: This method accepts three parameters as discussed below:

  • doc: It is used to specify the document object.
  • fields: It is used to specify various objects in the form of JavaScript objects.
  • skipid: It is used to specify _id should be there in documents.

Return Value: This method returns the subclass of the Document class.

Setting up Node.js application:

Step 1: Create a Node.js application using the following command:

npm init

Step 2: After creating the NodeJS application, Install the required module using the following command:

npm install mongoose

Project Structure: The project structure will look like this: 

👁 Image
 

Database Structure: The database structure will look like this, the following documents are present in the collection.

👁 Image
 

Example 1: In this example, we are illustrating the functionality of Mode() class. We are creating new document object of Customer model using subclass of Document class i.e Customer.

Filename: app.js

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output:

{
 name: 'Harshit',
 address: 'Pune',
 orderNumber: 45,
 _id: new ObjectId("63c1c0294a390b560860be13"),
 __v: 0
}

Example 2: In this example, we are illustrating the functionality of Model() class.  At the end, we are sending an object to Customer model constructor.

Filename: app.js

Step to run the program: To run the application execute the below command from the root directory of the project:

node app.js

Output: 

{
 name: 'Kalpesh',
 address: 'Mumbai',
 orderNumber: 85,
 _id: new ObjectId("63c1c13545be37f87a052528"),
 __v: 0
}

Reference: https://mongoosejs.com/docs/api/model.html#model_Model

Comment

Explore