Skip to content

Instantly share code, notes, and snippets.

@elrrrrrrr
Last active January 21, 2019 12:29
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save elrrrrrrr/792a275f8506e9562852 to your computer and use it in GitHub Desktop.
Save elrrrrrrr/792a275f8506e9562852 to your computer and use it in GitHub Desktop.
mongoose实现id自增
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
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
@xiaokaceng
Copy link

Hi, This code is incorrect,probably is “self.id = result.value.next;”

@rhinonan
Copy link

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