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?
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.
A . Mongoose doesn't handle unique on its own: { name: { type: String, unique: true } } is just a shorthand for creating a MongoDB unique index on name . For example, if MongoDB doesn't already have a unique index on name , the below code will not error despite the fact that unique is true.
The versionKey is a property set on each document when first created by Mongoose. This keys value contains the internal revision of the document.
By default, MongoDB creates an _id property on every document that's of type ObjectId. Many other databases use a numeric id property by default, but in MongoDB and Mongoose, ids are objects by default.
Only one field is inserted but it automatically generates an _id field. Let’s insert another document, but this time through mongoose. The second document also contains an auto-generated _id field. But it also contains one extra field.
If you’re unfamiliar with mongoose, it is an ORM or Object Relational Mapper used with MongoDb. It is extremely popular and can make your database queries much more manageable. Please check out their documentation if you’re interested in using mongoose.
Data in MongoDB is stored in JSON format. More precisely said, data is stored in BSON format. BSON format provides a variety of data types. We can insert data from mongo shell or through mongoose. In both cases, the _id field is generated automatically in each document. The _id field acts as a primary key.
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' })
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With