![]() |
VOOZH | about |
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:
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:
Database Structure: The database structure will look like this, the following documents are present in the collection.
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