用mongoose创建唯一的autoincrement字段 [英] Create unique autoincrement field with mongoose
本文介绍了用mongoose创建唯一的autoincrement字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定模式:
var EventSchema = new Schema({
id: {
// ...
},
name: {
type: String
},
});
我想让 id
。我尝试实现 mongodb实现,但有理解如何做的问题在猫鼬。
I want to make id
unique and autoincrement. I try to realize mongodb implementation but have problems of understanding how to do it right in mongoose.
我的问题是:在不使用任何插件等情况下,在mongoose中实现autoincrement字段的正确方法是什么?
My question is: what is the right way to implement autoincrement field in mongoose without using any plugins and so on?
推荐答案
这里是使用Mongoose自动递增字段实现的一个很好的例子:
Here is a good example of auto-incremented fields implementation using Mongoose:
var CounterSchema = Schema({
_id: {type: String, required: true},
seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);
var entitySchema = mongoose.Schema({
testvalue: {type: String}
});
entitySchema.pre('save', function(next) {
var doc = this;
counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter) {
if(error)
return next(error);
doc.testvalue = counter.seq;
next();
});
});
您应该执行 mongodb文档。
这篇关于用mongoose创建唯一的autoincrement字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文