javascript - 自动递增序列 Mongoose

标签 javascript node.js mongodb mongoose

我在 Mongoose 中实现了一个自动递增序列字段。我将默认/起始值设置为 5000。但它不是从 5000 开始,而是从 1 开始。

这是我的代码:

我的计数器架构

// app/models/caseStudyCounter.js
// load the things we need
var mongoose = require('mongoose');
var bcrypt   = require('bcrypt-nodejs');

// define the schema for our user model
var caseStudyCounterSchema = mongoose.Schema({
   _id: {type: String, required: true},
   seq: {type: Number, default: 5000}

});

// methods ======================

// create the model for users and expose it to our app
module.exports = mongoose.model('caseStudyCounter', caseStudyCounterSchema);

我的主要架构:

// grab the mongoose module
var caseStudyCounter = require('../models/caseStudyCounter');
var mongoose = require("mongoose");

// grab the bcrypt module to hash the user passwords
var bcrypt   = require('bcrypt-nodejs');

// define the schema for our model
var caseStudySchema = mongoose.Schema({
     caseStudyNo: Number,
     firstName: String,
     lastName: String,

 });

caseStudySchema.pre('save', function(next) {
  var doc = this;

caseStudyCounter.findByIdAndUpdate({_id: 'caId'},{$inc: { seq: 1}},{"upsert": true,"new": true  }, function(error, counter)   {
    if(error)
        return next(error);
    doc.caseStudyNo = counter.seq;
    next();
});

});
 // module.exports allows us to pass this to other files when it is called
 // create the model for users and expose it to our app
 module.exports = mongoose.model('CaseStudy', caseStudySchema);

当我将默认值设置为 5000 时,我不明白为什么它的起始格式为 1。顺序应该是 5001、5002、5003 等等。任何帮助将不胜感激。

最佳答案

可能这就是它发生的原因:https://github.com/Automattic/mongoose/issues/3617#issuecomment-160296684

Use the setDefaultsOnInsert option. Or just manually use {$inc: {n:1}, $setOnInsert: {n:776} }

关于javascript - 自动递增序列 Mongoose ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/37831951/

相关文章:

javascript - 如何从 AngularJS 模板中的嵌套 JSON 数组中获取值?

node.js - 如何为 fs.readFileSync() 捕获没有文件?

javascript - 此处出现意外的“super”关键字

javascript - 为什么 req.body 不断返回空对象?

node.js - 如何使用nodejs更新mongodb中的数据

javascript - Babel [karma-babel-preprocessor] 不为 Karma 测试转换 ES6->ES5

javascript - 拖放文件上传

javascript - promise 链: parent promise is not waiting until child promise gets executed

javascript - 当 vuex store 改变时更新 prop 属性

java - $set 和位置运算符在 Java 中不起作用?