In Mongoose, every document saved to MongoDB automatically receives an _id property, which is the default property of type ObjectId. When you create and save a new document using a Mongoose model, Mongoose internally invokes MongoDB's insert operation, which generates a new ObjectId. This _id is unique and is automatically added to your document.
Retrieving the _id (i.e., ObjectId) of a document after saving it is straightforward. When you call the .save() method and obtain the result of the save operation through a callback or a Promise, you can directly access the _id property of the document.
Here is an example using Promises:
javascriptconst mongoose = require('mongoose'); const { Schema } = mongoose; // Define a simple schema const mySchema = new Schema({ name: String }); // Create the model const MyModel = mongoose.model('MyModel', mySchema); // Create a document instance const myDocument = new MyModel({ name: 'John Doe' }); // Save the document myDocument.save().then((savedDocument) => { // After saving the document, we can directly access _id console.log('Document saved with _id:', savedDocument._id); }).catch((error) => { console.error('Error saving document:', error); });
In the above example, when the .save() method executes successfully, it returns a Promise object containing the saved document. In the .then part of this Promise, we can access the newly created ObjectId via savedDocument._id. If the save operation fails, it enters the .catch block, where we can handle the error.
In the async/await example, we use the await keyword within an async function saveDocument to wait for the execution result of myDocument.save(). If the execution is successful, we can directly access the _id property via savedDocument._id. If an error occurs during execution, it enters the catch block, where we can handle the error.