根据 http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning当数组元素移出其原始位置时,版本字段 __v 应该会发生变化。
我运行了一个测试代码(Mongoose 版本 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 被删除,如果任何代码试图通过其索引的位置访问它,就会对数组进行破坏性更改。为什么版本没有递增?
最佳答案
文章的作者并没有很清楚什么时候会在内部应用版本增量,因为你发现当你使用更新命令时版本字段没有更新。
如果将更新命令替换为 Mongoose pull数组上的方法版本字段将递增:
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 ] }
编辑:
模型上的更新方法基本上只构建和执行查询。使用保存方法时会完成版本检查/递增
关于javascript - Mongoose __v 什么时候变,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/25419846/