我有点不知所措。我期望每次更新 Mongoose 中的对象时,版本都会在 __v 上增加。事实似乎并非如此。我错过了什么还是这是一个错误?
var mongoose = require('mongoose');
mongoose.Promise = require('bluebird');
mongoose.connect('mongodb://localhost/mongooseTest');
var Cat = mongoose.model('Cat', {
name: String,
manualVersion: Number,
arr: []
});
var kitty = new Cat({
name: 'Zildjian',
manualVersion: 0,
arr: []
});
kitty.save()
.then(x => {
x.manualVersion = x.manualVersion + 1;
//x.arr.push(x.manualVersion); <-- pushing here makes '__v' be correct
return x.save();
})
.then(() => Cat.findOne({}))
.then(x => {
x.manualVersion = x.manualVersion + 1;
//x.arr.push(x.manualVersion); <-- pushing here makes '__v' be correct
return x.save();
})
.then(() => Cat.findOne({}))
.then(x => {
console.log(x.toObject());
// RESULT (from console.log and what is also in the DB):
// {
// _id: 565386b058b2632c0886b160,
// name: 'Zildjian',
// manualVersion: 2,
// __v: 0,
// arr: []
// }
});
最佳答案
x.increment().save();
上面的例子解决了我的问题。 “save()”似乎也是幂等的,因此只要您知道自己正在进行更改,就可以调用每次保存,这很酷。根据 Mongoose 版本控制的一位作者的说法,它仅适用于数组,并且只能用于数组的增量。呃。
http://aaronheckmann.tumblr.com/post/48943525537/mongoose-v3-part-1-versioning
至少这应该在 IMO 文档中清楚地说明,因为它目前非常模糊......
关于node.js - Mongoose 版本控制损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881489/