本文介绍了用猫鼬创建唯一的自动增量字段的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
给定一个架构:
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 中实现自动增量字段的正确方法是什么?
My question is: what is the right way to implement autoincrement field in mongoose without using any plugins and so on?
推荐答案
const ModelIncrementSchema = new Schema({
model: { type: String, required: true, index: { unique: true } },
idx: { type: Number, default: 0 }
});
ModelIncrementSchema.statics.getNextId = async function(modelName, callback) {
let incr = await this.findOne({ model: modelName });
if (!incr) incr = await new this({ model: modelName }).save();
incr.idx++;
incr.save();
return incr.idx;
};
const PageSchema = new Schema({
id: { type: Number , default: 0},
title: { type: String },
description: { type: String }
});
PageSchema.pre('save', async function(next) {
if (this.isNew) {
const id = await ModelIncrement.getNextId('Page');
this.id = id; // Incremented
next();
} else {
next();
}
});
这篇关于用猫鼬创建唯一的自动增量字段的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!