What Is the __v Field in Mongoose

What Is the __v Field in Mongoose

Mongoose is a high-level ODM (Object Data Modeling) library for Node.js and MongoDB. If you’re using Mongoose, you may notice that a field named __v has been automatically added to your documents. In this article, we are going to explain, what is __v field, its usage, how it interacts with Mongoose, and how you can suppress or control it when needed.

What is  __v Field?

The __v field is a version key added by Mongoose to documents in MongoDB. A version key in MongoDB added by Mongoose as __v is used to track the version of a document. It is automatically included unless explicitly disabled.

Purpose of the __v Field

The purpose of the __v field is to track the version of a document which prevents conflicts when multiple users try to update the same document at the same time.

For instance:

  • The __v value in the database must match the version of the document being currently updated in Mongoose. If the versions do not match, it indicates a conflict preventing accidental overwrites.

How Mongoose Uses the __v Field

The __v field is automatically incremented in Mongoose when a document is updated using the save method.

Example of __v

Let’s take a simple schema and a saved document:

Initial Document:

const user = new User({ name: 'aman', email: '[email protected]' });

await user.save();

This creates a document with:

{
  "_id": "your_id",
  "name": "aman",
  "email": "[email protected]",
  "__v": 0
}

First Update:

const user1 = await User.findById("your_id");
user1.name = icon;
await user1.save(); // The version key (__v) is incremented

The document is now:

{
  "_id": "your_id",
  "name": "icon",
  "email": "[email protected]",
  "__v": 1
}

Second Update with Conflicting Version:

const user2 = await User.findById("your_id");
user2.email = ‘[email protected]';
user2.__v = 0;

#Here, user2 is manually setting the version key to 0, as if it’s an older version

await user2.save();

Saving this will trigger an error, because the version value doesn’t match.

In this case, an error will occur because the __v field doesn’t match the current version of the document (1), preventing the accidental overwriting of changes.

This example shows how the __v field helps to manage updates and prevents conflicts when multiple users try to update the same document.

Managing the __v Field

Removing the __v Field

If you don’t need versioning, you can disable the __v field by setting the versionKey option to false in your schema definition::

const schema = new mongoose.Schema({ name: String }, { versionKey: false });

This will prevent Mongoose from adding the __v field to your documents.

Keeping __v While Hiding It in API Responses

You may wish to retain the __v field for certain internal purposes, but not want it to appear in API responses. This can be done using the toJSON or toObject transform options:

const schema = new mongoose.Schema({ name: String });
schema.set('toJSON', {
  transform: (doc, ret) => {
    delete ret.__v;
    return ret;
  },
});

Now, the __v field will not appear in JSON outputs but will still exist in the database.

Conclusion

The __v field in Mongoose is a version key to keep track of the updates on a document and thus handle optimistic concurrency. It can be disabled or hidden if not needed for an application. Knowledge of how to handle the __v field would help you gain better control over your data and application behavior. If you want to learn these specifics of Web Development, then you should head to our Full Stack Developer Course.

FAQs

1. Can I rename the __v field?

Yes, you can rename the version key with the version Key option:

const schema = new mongoose.Schema({ name: String }, { versionKey: 'version' });
2. Will the __v field be added to all collections?

No, the __v field only applies to schema definitions in Mongoose. Mongoose does not add it to collections managed otherwise.

3. Is the __v field updated during direct updates via updateOne or updateMany?

No, the __v field is not updated during direct updates using updateOne or updateMany

4. How do I use the __v field for optimistic concurrency?

To use __v for concurrency control, make sure to turn on optimisticConcurrency in your schema options:

const schema = new mongoose.Schema({ name: String }, { optimisticConcurrency: true });
5. Does disabling __v affect performance?

Disabling the __v field has no performance impact but removes the ability to use versioning for concurrency management.

About the Author

Technical Research Analyst - Full Stack Development

Kislay is a Technical Research Analyst and Full Stack Developer with expertise in crafting Mobile applications from inception to deployment. Proficient in Android development, IOS development, HTML, CSS, JavaScript, React, Angular, MySQL, and MongoDB, he’s committed to enhancing user experiences through intuitive websites and advanced mobile applications.

Full Stack Developer Course Banner