我在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,依此类推。任何帮助将不胜感激。
答案 0 :(得分:2)
可能这就是它发生的原因:https://github.com/Automattic/mongoose/issues/3617#issuecomment-160296684
使用
setDefaultsOnInsert
选项。或者只需手动使用{$inc: {n:1}, $setOnInsert: {n:776} }
答案 1 :(得分:0)
您可以安装mongoose-auto-increment。
yourSchema.plugin(autoIncrement.plugin, {
model: 'model',
field: 'field',
startAt: 5000,
incrementBy: 1
});
易于安装和使用。
答案 2 :(得分:0)
这是一个非常普遍的需求,因此可能值得使用现有模块。我玩了一些,但这是最容易进行我的项目工作的地方。 https://www.npmjs.com/package/mongoose-sequence。请记住,如果要重新设置_id
字段的用途,则必须根据文档在架构中将其声明为Number
类型。
答案 3 :(得分:0)
我也面临着同样的问题,所以我想出了这个解决方案。
var mongoose = require("mongoose");
// define the schema for our model
var caseStudySchema = mongoose.Schema({
caseStudyNo: {
type:Number,
default:5000
},
firstName: String,
lastName: String,
});
caseStudySchema.pre('save', function(next) {
var doc = this;
//Retrieve last value of caseStudyNo
CaseStudy.findOne({},{},{sort: { 'caseStudyNo' :-1}}, function(error, counter) {
//if documents are present in collection then it will increament caseStudyNo
// else it will create a new documents with default values
if(counter){
counter.caseStudyNo++;
doc.caseStudyNo=counter.caseStudyNo;
}
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
const CaseStudy = mongoose.model('CaseStudy', caseStudySchema);
module.exports = CaseStudy;
答案 4 :(得分:-1)