猫鼬__v什么时候改变 [英] Mongoose __v when does it change

查看:84
本文介绍了猫鼬__v什么时候改变的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

根据 http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning 版本字段__v假定在数组元素移出其原始位置时发生更改.

According to http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning The version field __v is suppose to change when array elements are shifted out of their original position.

我运行测试代码(猫鼬版本3.8.15):

I run a 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();
    });
  });
});

输出:

{ __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 ] } ]

因此,删除了数字3,如果有任何代码要尝试通过其索引的位置来访问该数组,则该数组会带来破坏性的变化.为什么版本没有增加?

So, number 3 is removed which introduced a disruptive change to the array if any code is to attempt to access it by the position of its index. Why isn't the version incremented?

推荐答案

本文的作者并不清楚在内部应用版本增量的时间,因为您发现当您执行以下操作时,版本字段不会更新重新使用更新命令.

The author of the article wasn't very clear when the version increment will be internally applied, because as you found out the version field is not updated when you're using the update command.

如果在数组上用Mongoose pull 方法替换了更新命令,版本字段将增加:

If you replace the update command with Mongoose pull method on your array 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)
    });
});

结果:

{ __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 ] }

模型上的update方法基本上只构建并执行查询.当您使用save方法时,将完成版本检查/递增

The update method on the model basically only builds and executes the query. The version checking / incrementing is done when you use the save method

这篇关于猫鼬__v什么时候改变的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆