【发布时间】:2017-06-01 03:04:49
【问题描述】:
谁能告诉我如何在不使用任何库或插件的情况下在 mongoose 中创建一个自动增量字段。任何简单易行的方法..
【问题讨论】:
标签: node.js mongoose mongoose-schema mongoose-auto-increment
谁能告诉我如何在不使用任何库或插件的情况下在 mongoose 中创建一个自动增量字段。任何简单易行的方法..
【问题讨论】:
标签: node.js mongoose mongoose-schema mongoose-auto-increment
使用 mongoose pre save 功能可以在 mongoose 中实现自动增量,这是一种非常简单易行的方法。这是我的用户收集代码,在您的 mongoose 模型(模式) 中尝试相同的技巧来实现自动增量。将此代码粘贴到您的集合架构文件中并替换一些变量(userSchema, user)根据您的集合架构。
userSchema.pre('save', function(next) {
var currentDate = new Date();
this.updated_at = currentDate;
if (!this.created_at)
this.created_at = currentDate;
var sno = 1;
var user = this;
User.find({}, function(err, users) {
if (err) throw err;
sno = users.length + 1;
user.sno = sno;
next();
});
});
【讨论】:
如果您使用软删除功能 上述答案可能有效,但要解决它,有几种方法。
1:在插入新记录之前获取最后一个文档(行)并放入id = 1 + (id of the last record)。
2:可以使用插件mongoose-auto-increment。
3:最后但并非最不重要选项将最后增加的值保存在单独的集合中(集合名称:autoIncrement 列将是集合和 sno),在创建记录之前获取该集合增量的 sno 值它,创建您的记录并在 autoIncrement 集合中再次更新 sno 值。
奖励:
1:可以在redis中创建autoIncrement。
2:这个答案的第一点将无法解决几个问题,即:您的应用会在删除时执行某种行为,如果用户从集合的开头或中间删除一行,它将删除该 id( sno. 表格),但万一用户删除了最后一条记录。它会放那个sno。在下一条记录中。
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();
});
});
【讨论】: