Mongoose Model.createCollection() API
Last Updated :
25 Aug, 2022
The Model.createCollection() method of the Mongoose API is used to create a collection for the model. Mongoose by default does not create any collection for the model in the database until any documents are created. The createCollection() method is used to create a collection explicitly.
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:
Example 1: In this example, We have established a database connection using mongoose and defined model over userSchema. In the end, we are creating a collection on the User model.
- app.js: Write down the below code in the app.js file:
app.js
const mongoose = require( 'mongoose' );
mongoose.connect(
useNewUrlParser: true ,
useUnifiedTopology: true
})
const userSchema = new mongoose.Schema(
{ name: String, age: Number }
)
const User = mongoose.model( 'User' , userSchema);
User.createCollection().then( function (collection) {
console.log( 'Collection is created!' );
});
|
Steps to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
1. On Console:
Collection is created!
2. You can use any GUI tool for the representation of the database in graphical form. Here, I have used the Robo3T GUI tool for graphical representation.
Example 2: In this example, We have established a database connection and added a callback function which will execute once the database connection is established and defined model over userSchema. In the end, we are creating a collection on the User model.
- app.js: Write down the below code in the app.js file:
app.js
const mongoose = require( 'mongoose' );
const Schema = mongoose.Schema;
useNewUrlParser: true ,
useUnifiedTopology: true
}).then((result) => {
console.log( 'Connection Established' )
}). catch ((err) => {
console.log(err)
});
const userSchema = new Schema(
{ name: String, age: Number, email: String }
)
const User = mongoose.model( 'User' , userSchema);
User.createCollection().then( function (collection) {
console.log( 'Collection is created!' );
});
|
Steps to run the program: To run the application execute the below command from the root directory of the project:
node app.js
Output:
1. On Console:
Connection Established
Collection is created!
2. You can use any GUI tool for the representation of the database in graphical form. Here, I have used the Robo3T GUI tool for graphical representation.
Reference: https://mongoosejs.com/docs/api/model.html#model_Model-createCollection
Share your thoughts in the comments
Please Login to comment...