node.js - Mongoose 版本控制损坏了吗?

标签 node.js mongodb mongoose

我有点不知所措。我期望每次更新 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 文档中清楚地说明,因为它目前非常模糊......

http://mongoosejs.com/docs/guide.html#versionKey

关于node.js - Mongoose 版本控制损坏了吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33881489/

相关文章:

javascript - ES6 和 sequelize-cli

mysql - 从 Mysql 中获取日期时间

javascript - 我的 req.params.id 未定义。我该如何修复我的路线以使其正常工作

node.js - FindOneAndUpdate 不更新带有传入参数的嵌套字段

node.js - 通过回调或 Mongoose 模型验证 PassportJS?

Javascript 参数作为未定义传递

node.js - 如何获得使用 Node fs创建文件/目录的权限

mongodb - 将关注者计数保存在字段中或根据需要每次查询

node.js - 填充 Mongoose 的条件

node.js - 值被添加到数据库条目的末尾,而不是更新相关列