Open In App

Mongoose Schemas Ids

Improve
Improve
Like Article
Like
Save
Share
Report

Mongoose is a MongoDB object modeling and handling for a node.js environment. Mongoose automatically adds an _id property of type ObjectId to a document when it gets created. This can be overwritten with a custom id as well, but note that without an id, mongoose doesn’t allow us to save or create a new document.

Creating node application And Installing Mongoose:

Step 1: Create a node application using the following command:

mkdir folder_name
cd folder_name
npm init -y

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

npm install mongoose

Project Structure: It will look like the following.

 

Example 1: In this example, we will create some documents and log their _id, which is set by the mongoose automatically, to the console

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : 
    console.log('Connected to database'));
  
const animalSchema = new mongoose.Schema({ 
    name: String, type: String });
  
const Animal = mongoose.model("Animal", animalSchema);
  
const animals = [
    {
        name: 'bond',
        type: 'dog'
    },
    {
        name: 'cavine',
        type: 'cat'
    }
]
  
Animal.insertMany(animals, (err, res) => {
    res.forEach(animal => {
        console.log(animal._id)
    })
})


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Example 2: In this example, we will create a custom _id while creating a new document and log it to the console.

Filename: main.js

Javascript




const mongoose = require('mongoose')
  
// Database connection
    dbName: 'event_db',
    useNewUrlParser: true,
    useUnifiedTopology: true
}, err => err ? console.log(err) : console.log(
    'Connected to database'));
  
const schema = new mongoose.Schema({ _id: Number });
const Model = mongoose.model('Test', schema);
  
const doc = new Model();
doc._id = 1;
doc.save().then((res) => {
    console.log(res);
});


Step to Run Application: Run the application using the following command from the root directory of the project:

node main.js

Output:

 

Reference: https://mongoosejs.com/docs/guide.html#_id



Last Updated : 02 Nov, 2022
Like Article
Save Article
Previous
Next
Share your thoughts in the comments
Similar Reads