Gle*_*ift 23 database auto-increment mongoose mongodb node.js
给出一个架构:
var EventSchema = new Schema({
    id: {
        // ...
    },
    name: {
        type: String
    },
});
我想做出id独特的自动增量.我尝试实现mongodb实现,但是有理解如何在mongoose中正确执行它的问题.
我的问题是:在不使用任何插件等的情况下,在mongoose中实现自动增量字段的正确方法是什么?
edt*_*ech 32
以下是使用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文档执行步骤1 .
小智 5
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();
    }
});
是的,这就是该功能的“瘦”。
您需要在 mongo 数据库中拥有该集合。如果需要,它可以充当并发密钥分配单一事实记录。Mongo 的示例向您展示了如何执行“原子”操作来获取下一个密钥,并确保即使存在并发请求,也能保证返回唯一的密钥而不会发生冲突。
但是,mongodb 本身并没有实现该机制,它们向您展示了如何做到这一点。它们仅提供 _id 用作唯一文档密钥。我希望这能澄清你的方法。
为了扩展这个想法,请继续将 mongo 建议的实现添加到您定义的 Mongoose 模型中,正如您已经猜到的那样,在预保存或更好的预初始化事件中使用它,以确保如果您使用在将其保存到 mongo 之前收集服务器端。
| 归档时间: | 
 | 
| 查看次数: | 26515 次 | 
| 最近记录: |