Last active
January 21, 2019 12:29
-
-
Save elrrrrrrr/792a275f8506e9562852 to your computer and use it in GitHub Desktop.
mongoose实现id自增
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var Sequence = require('./sequence'); | |
var pieceSchema = mongoose.Schema({ | |
id: { type : Number, index: { unique: true } }, | |
content: String, | |
link: String, | |
pics:[String] , | |
author: mongoose.Schema.ObjectId , | |
work: Boolean, | |
updated: { type: Date, default: Date.now }, | |
created: { type: Date, default: Date.now } | |
}) | |
//在创建文档时,获取自增ID值 | |
pieceSchema.pre('save', function(next) { | |
var self = this; | |
if( self.isNew ) { | |
Sequence.increment('Piece',function (err, result) { | |
if (err) | |
throw err; | |
self.id = result.next; | |
next(); | |
}); | |
} else { | |
next(); | |
} | |
}) | |
var Piece = mongoose.model('Piece', pieceSchema); | |
module.exports = Piece |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
var mongoose = require('mongoose'); | |
var Schema = mongoose.Schema; | |
var models = {}; | |
/** | |
* 存储ID的序列值 | |
*/ | |
SequenceSchema = new Schema({ | |
_id: String, | |
next: Number | |
}); | |
SequenceSchema.statics.findAndModify = function (query, sort, doc, options, callback) { | |
return this.collection.findAndModify(query, sort, doc, options, callback); | |
}; | |
SequenceSchema.statics.increment = function (schemaName, callback) { | |
return this.collection.findAndModify({ _id: schemaName }, [], | |
{ $inc: { next: 1 } }, {"new":true, upsert:true}, callback); | |
}; | |
var Sequence = mongoose.model('Sequence', SequenceSchema); | |
module.exports = Sequence | |
self.id = result.value.next
it work fine
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Hi, This code is incorrect,probably is “self.id = result.value.next;”