I want to start taking advantage of Mongooses document versioning (__v key). I was having an issue actually incrementing the version value, then I found that you have to add this.increment()
when executing a query.
Is there a way to have automatically incremented? For now, I just added it to the pre middleware for a update-type queries:
module.exports = Mongoose => {
const Schema = Mongoose.Schema
const modelSchema = new Schema( {
name: Schema.Types.String,
description: Schema.Types.String
} )
// Any middleware that needs to be fired off for any/all update-type queries
_.forEach( [ 'save', 'update', 'findOneAndUpdate' ], query => {
// Increment the Mongoose (__v)ersion for any updates
modelSchema.pre( query, function( next ) {
this.increment()
next()
} )
} )
}
Which seems to work.. But I kinda thought there would already be a way to do this within Mongoose.. am I wrong?
Mongoose plugin that auto-increments any ID field on your schema every time a document is saved. This is the module used by mongoose-simpledb to increment Number IDs. You are perfectly able to use this module by itself if you would like.
Upsert is a combination of insert and update (inSERT + UPdate = upsert). We can use the upsert with different update methods, i.e., update, findAndModify, and replaceOne. Here in MongoDB, the upsert option is a Boolean value. Suppose the value is true and the documents match the specified query filter.
In Mongoose the “_v” field is the versionKey is a property set on each document when first created by Mongoose. This is a document inserted through the mongo shell in a collection and this key-value contains the internal revision of the document.24-Jun-2021.
You can update value by using { $inc: {views:1}} in mongoose.
I'd say this is the way to go. pre middleware fits exactly this need, and I don't know any other way. In fact this is what I'm doing in all my schemas.
What you need to be aware of though, is the difference between document and query middleware.
Document middleware are executed for init
, validate
, save
and remove
operations. There, this
refers to the document:
schema.pre('save', function(next) {
this.increment();
return next();
});
Query middleware are executed for count
, find
, findOne
, findOneAndRemove
, findOneAndUpdate
and update
operations. There, this
refers to the query object. Updating the version field for such operations would look like this:
schema.pre('update', function( next ) {
this.update({}, { $inc: { __v: 1 } }, next );
});
Source: mongoose documentation.
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