Mongoose __v when it changes

According to http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning The __v version field should be changed when array elements are offset from their original position.

I am running test code (Mongoose version 3.8.15):

var mongoose = require('mongoose');

var db = mongoose.connection;
mongoose.connect('mongodb://localhost:27017/node_test');
db.on('error', console.error.bind(console, 'connection error:'));

var testSchema = mongoose.Schema({
  name: String,
  arr: [Number]
})
var Test = mongoose.model('Test', testSchema);

var t = Test();
t.name = 'hi'
t.arr = [1, 2, 3, 4, 5, 6];
t.save(function (err, result) {
  console.log(result)
  Test.update({'name': 'hi'}, {$pull: {'arr': 3}}, function(err2, result2) {
    console.log(result2)
    Test.find({'name': 'hi'}, function(err3, result3) {
      console.log(result3);
      db.close();
    });
  });
});

      

Output:

{ __v: 0,
  name: 'hi',
  _id: 53f594a0113832871c2eea89,
  arr: [ 1, 2, 3, 4, 5, 6 ] }
1
[ { _id: 53f594a0113832871c2eea89,
    name: 'hi',
    __v: 0,
    arr: [ 1, 2, 4, 5, 6 ] } ]

      

So number 3 is removed, which makes a devastating change to the array if any code tries to access it by its index position. Why doesn't the version grow?

+3


source to share


1 answer


It was not very clear to the author of the article when the version increment would be applied internally, because as you learned, the version field is not updated when using the update command.

If you replace the update command with the Mongoose pull method on your array, then the version field will be incremented:

var t = Test();
t.name = 'hi'
t.arr = [1, 2, 3, 4, 5, 6];

t.save(function (err, result) {
    console.log(result);

    // use Mongoose pull method on the array
    t.arr.pull(3);

    t.save(function(err2, result2) {
        console.log(result2)
    });
});

      

Results:



{ __v: 0,
  name: 'hi',
  _id: 53f59d2a6522edb12114b98c,
  arr: [ 1, 2, 3, 4, 5, 6 ] }
{ __v: 1,
  name: 'hi',
  _id: 53f59d2a6522edb12114b98c,
  arr: [ 1, 2, 4, 5, 6 ] }

      

Edit:

The update method on the model basically just builds and executes the query. Version check / increment is done when using save method

+1


source







All Articles