425

I'm using Mongoose version 3 with MongoDB version 2.2. I've noticed a __v field has started appearing in my MongoDB documents. Is it something to do with versioning? How is it used?

Simon Lomax
  • 8,714
  • 8
  • 42
  • 75

8 Answers8

412

From here:

The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document. The name of this document property is configurable. The default is __v.

If this conflicts with your application you can configure as such:

new Schema({..}, { versionKey: '_somethingElse' })
Pierre
  • 18,643
  • 4
  • 41
  • 62
Tony The Lion
  • 61,704
  • 67
  • 242
  • 415
  • 34
    Is it safe to use this property to determine if a document was just created (e.g. `__v === 0`)? – Explosion Pills Aug 28 '13 at 18:24
  • 67
    @ExplosionPills for future reference: no. The version key is only incremented after operations that could cause a conflict, modifying array positions. Other updates won't increment it. The original release post explains it in detail: http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning – Ricardo Tomasi Sep 12 '13 at 19:04
  • 4
    Is there a way to hide it from the returned docs from the queries? – Diosney Dec 14 '13 at 20:41
  • 10
    @diosney `query.select('-__v')`. @ExplosionPills you would need to add mongoose middleware like `schema.pre('save', function (next) { this.increment(); next(); })`. – wprl Dec 20 '13 at 19:02
  • @diosney You could use the transform option of Document.toObject() to delete the __v property. http://mongoosejs.com/docs/api.html#document_Document-toObject – talentedmrjones Mar 22 '14 at 00:19
  • 4
    **@talentedmrjones** **@wprl** That is exactly what I'm doing now, but I wanted something that I could put in the Schema directly so in **all** queries. – Diosney Mar 24 '14 at 11:52
  • 1
    Also if you don't want it you can set: ```new Schema({..}, { versionKey: false }) ``` – Philipos D. Dec 06 '20 at 18:37
  • 1
    Why does it works with array only ? Why not with other fields ? – Dhruv Thakkar Nov 16 '21 at 05:05
105

Well, I can't see Tony's solution...so I have to handle it myself...


If you don't need version_key, you can just:

var UserSchema = new mongoose.Schema({
    nickname: String,
    reg_time: {type: Date, default: Date.now}
}, {
    versionKey: false // You should be aware of the outcome after set to false
});

Setting the versionKey to false means the document is no longer versioned.

This is problematic if the document contains an array of subdocuments. One of the subdocuments could be deleted, reducing the size of the array. Later on, another operation could access the subdocument in the array at it's original position.

Since the array is now smaller, it may accidentally access the wrong subdocument in the array.

The versionKey solves this by associating the document with the a versionKey, used by mongoose internally to make sure it accesses the right collection version.

More information can be found at: http://aaronheckmann.blogspot.com/2012/06/mongoose-v3-part-1-versioning.html

Darryl Bayliss
  • 2,677
  • 2
  • 19
  • 28
kenberkeley
  • 8,449
  • 3
  • 35
  • 25
17

For remove in NestJS need to add option to Schema() decorator

@Schema({ versionKey: false })
FloatingRock
  • 6,741
  • 6
  • 42
  • 75
Lysak
  • 333
  • 1
  • 4
  • 7
9

It is possible to disable the version key if you don't need it.

See this example:

var User = new mongoose.Schema({
   FullName:{
       type :String,
      
   },
   BirthDay:{
       type :String,
       
   },
   Address:{
       type :String,
   },
   Gender:{
       type:String,
   },
   PhoneNumber:{
       type:Number,
       ref:'Account'
   },
   AccountID:{
        type: Schema.Types.ObjectId,
        ref: 'Account'
   },
   UserName:{
       type:String,
       ref:'Account'
   }
},{collection:'User',
   versionKey: false //here
});
Dirk Scholten
  • 1,013
  • 10
  • 19
Nguyen Phu
  • 106
  • 2
  • 4
4

the '__v' field in our 'document' serves 'optimisticConcurrency' concerns.

This term basically means in mongoose : let, you grabed a document by 'findOne, findById' but not used save() method of mongoose yet. and what if at this interval, any other code grabed same document and used .save() method before the first document instance. at this use case, if we want to (mongoose specific) throw a version error kinda thing, we use optimisticConcurrency: true option in schema.

and then mongoose will use '__v1' to compare these two document.

without optimisticConcurrency: true option. '__v' has no has no effect. and mongoose will not increase it by 1.

Note : in 'findOneAndUpdate' kinda operations, will not update '__v'. (only save() updates)

ratyacatnug
  • 121
  • 1
  • 5
3

It is the version key.It gets updated whenever a new update is made. I personally don't like to disable it .

Read this solution if you want to know more [1]: Mongoose versioning: when is it safe to disable it?

2

The __v field is called the version key. It describes the internal revision of a document. This __v field is used to track the revisions of a document. By default, its value is zero (__v:0).

If you don't want to use this version key you can use the versionKey: false as mongoose.Schema parameter.

You can follow this example...

const mongoose = require('mongoose');

const userSchema = mongoose.Schema(
    {
        name: {
            type: String,
            require: true
        },
        email: {
            type: String,
            unique: true
        },

        password: {
            type: String,
        }
    },
    {
        timestamps: true,
        versionKey: false, // Here You have to add.
    }
)

module.exports = mongoose.model('tbl_user', userSchema)
0

We can use versionKey: false in Schema definition

'use strict';

const mongoose = require('mongoose');

export class Account extends mongoose.Schema {

    constructor(manager) {

        var trans = {
            tran_date: Date,
            particulars: String,
            debit: Number,
            credit: Number,
            balance: Number
        }

        super({
            account_number: Number,
            account_name: String,
            ifsc_code: String,
            password: String,
            currency: String,
            balance: Number,
            beneficiaries: Array,
            transaction: [trans]
        }, {
            versionKey: false // set to false then it wont create in mongodb
        });

        this.pre('remove', function(next) {
            manager
                .getModel(BENEFICIARY_MODEL)
                .remove({
                    _id: {
                        $in: this.beneficiaries
                    }
                })
                .exec();
            next();
        });
    }

}
KARTHIKEYAN.A
  • 18,210
  • 6
  • 124
  • 133