自动增加Mongo/Mongoose中的文件编号 [英] Auto increment document number in Mongo / Mongoose

查看:76
本文介绍了自动增加Mongo/Mongoose中的文件编号的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的应用程序有多个用户,每个用户都有文档.每个文档都需要有一个序列号,可能看起来像这样:2013-1、2013-2(年份和序列号),或者可能只是一个简单的数字:1、2、3 ...

My app has several users, each user has documents. Each documents needs to have a sequence number, that may look something like this: 2013-1, 2013-2 (year and sequence number), or perhaps just a simple number: 1, 2, 3...

目前,我正在创建Mongoose文档时从用户设置中分配序列号.根据该序列号和用户设置的数字格式,我将生成最终的文档编号.

Currently, I am assigning the sequence number from user's settings when the Mongoose docuemnt is created. Based on that sequence number and the number format from user's settings, I am generating the final document number.

我意识到,当同时创建2个文档时,它们将获得完全相同的编号,因为在保存文档后,我将在设置中增加序列号.但是我在创建(尚未保存)文档时分配了序列号,因此两个文档的序列号将完全相同.

What I realized is that when 2 documents are created at the same time, they will get exactly the same number, because I am incrementing the sequence number in settings just after I have saved a document. But I am assigning the sequence number when I am creating (not saving yet) the document so the sequence number will be exactly the same for both documents.

我显然需要一种在保存时处理此序号自动递增的方法...

I obviously need a way to handle this sequence number auto-incrementing at the moment of saving...

我如何确保该数字是唯一的并且会自动递增/生成?

How can I assure that this number is unique and automatically incremented/generated?

推荐答案

@emre和@WiredPraire向我指出了正确的方向,但我想为我的问题提供与Mongoose兼容的完整答案.我得到了以下解决方案:

@emre and @WiredPraire pointed me to the right direction, but I wanted to provide a full Mongoose-compatible answer to my question. I ended up with the following solution:

var Settings = new Schema({
  nextSeqNumber: { type: Number, default: 1 }
});

var Document = new Schema({
  _userId: { type: Schema.Types.ObjectId, ref: "User" },
  number: { type: String }
});

// Create a compound unique index over _userId and document number
Document.index({ "_userId": 1, "number": 1 }, { unique: true });

// I make sure this is the last pre-save middleware (just in case)
Document.pre('save', function(next) {
  var doc = this;
  // You have to know the settings_id, for me, I store it in memory: app.current.settings.id
  Settings.findByIdAndUpdate( settings_id, { $inc: { nextSeqNumber: 1 } }, function (err, settings) {
    if (err) next(err);
    doc.number = settings.nextSeqNumber - 1; // substract 1 because I need the 'current' sequence number, not the next
    next();
  });
});

请注意,使用此方法无法在架构中要求数字路径,也没有要点,因为它是自动添加的.

Please note that with this method there is no way to require the number path in the schema, and there is no point as well, because it is automatically added.

这篇关于自动增加Mongo/Mongoose中的文件编号的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆