[英]Auto Increment Sequence 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
使用
setDefaultsOnInsert
選項。 或者只是手動使用{$inc: {n:1}, $setOnInsert: {n:776} }
您可以安裝mongoose-auto-increment 。
yourSchema.plugin(autoIncrement.plugin, {
model: 'model',
field: 'field',
startAt: 5000,
incrementBy: 1
});
它易於安裝和使用。
這是一個常見的需求,使用現有模塊可能是值得的。 我玩了幾個,但這是最容易使用我的項目。 https://www.npmjs.com/package/mongoose-sequence 。 請記住,如果要重新調整_id
字段的用途,則必須根據文檔將其聲明為模式中的Number
類型。
我也面臨同樣的問題,所以我想出了這個解決方案。
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;
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.