我在mongoose中实现了一个自增序列字段。我将默认/起始值设置为5000。但它没有从5000开始,而是从1开始。
以下是我的代码:
Counter Schema:
我无法理解为什么它从1开始,当我已经将默认值设为5000。 序列应该是5001,5002,5003等等。 如有帮助,将不胜感激。
以下是我的代码:
Counter Schema:
// 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);
我无法理解为什么它从1开始,当我已经将默认值设为5000。 序列应该是5001,5002,5003等等。 如有帮助,将不胜感激。