8

私のアプリには複数のユーザーがいて、各ユーザーにはドキュメントがあります。各ドキュメントには、次のようなシーケンス番号が必要です: 2013-1、2013-2 (年とシーケンス番号)、または単純な番号: 1、2、3...

現在、Mongooseドキュメント作成時にユーザー設定から連番を割り当てています。そのシーケンス番号とユーザー設定の番号形式に基づいて、最終的なドキュメント番号を生成しています。

ドキュメントを保存した直後に設定でシーケンス番号をインクリメントしているため、2つのドキュメントを同時に作成すると、まったく同じ番号が取得されることに気付きました。ただし、ドキュメントを作成するとき (まだ保存しないとき) にシーケンス番号を割り当てているため、両方のドキュメントでシーケンス番号がまったく同じになります。

保存時にこのシーケンス番号の自動インクリメントを処理する方法が明らかに必要です...

この番号が一意であり、自動的に増分/生成されることをどのように保証できますか?

4

4 に答える 4

12

@emre と @WiredPraire は正しい方向を示してくれましたが、質問に対して完全な Mongoose 互換の回答を提供したかったのです。私は次の解決策になりました:

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();
  });
});

この方法では、スキーマで数値パスを要求する方法がなく、自動的に追加されるため意味もありません。

于 2013-01-22T13:12:21.640 に答える
3

あなたはそれを達成することができます:

  1. シーケンスジェネレーターを作成します。これは、最後の番号のカウンターを保持する別のドキュメントです。
  2. マングース ミドルウェアを使用して、目的のフィールドの自動インクリメントを更新します。

これは、todo アプリで動作し、テストされた例です。

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/todoApp');

// Create a sequence
function sequenceGenerator(name){
  var SequenceSchema, Sequence;

  SequenceSchema = new mongoose.Schema({
    nextSeqNumber: { type: Number, default: 1 }
  });

  Sequence = mongoose.model(name + 'Seq', SequenceSchema);

  return {
    next: function(callback){
      Sequence.find(function(err, data){
        if(err){ throw(err); }

        if(data.length < 1){
          // create if doesn't exist create and return first
          Sequence.create({}, function(err, seq){
            if(err) { throw(err); }
            callback(seq.nextSeqNumber);
          });
        } else {
          // update sequence and return next
          Sequence.findByIdAndUpdate(data[0]._id, { $inc: { nextSeqNumber: 1 } }, function(err, seq){
            if(err) { throw(err); }
            callback(seq.nextSeqNumber);
          });
        }
      });
    }
  };
}

// sequence instance
var sequence = sequenceGenerator('todo');

var TodoSchema = new mongoose.Schema({
  name: String,
  completed: Boolean,
  priority: Number,
  note: { type: String, default: '' },
  updated_at: { type: Date, default: Date.now }
});

TodoSchema.pre('save', function(next){
  var doc = this;
  // get the next sequence
  sequence.next(function(nextSeq){
    doc.priority = nextSeq;
    next();
  });
});

var Todo = mongoose.model('Todo', TodoSchema);

次のようにノードコンソールでテストできます

function cb(err, data){ console.log(err, data); }
Todo.create({name: 'hola'}, cb);
Todo.find(cb);

新しく作成されたオブジェクトごとに、優先度が高くなります。乾杯!

于 2014-10-29T00:51:08.100 に答える
2

mongoose-auto-increment次のようにパッケージを使用できます。

var mongoose      = require('mongoose');
var autoIncrement = require('mongoose-auto-increment');

/* connect to your database here */

/* define your DocumentSchema here */

autoIncrement.initialize(mongoose.connection);
DocumentSchema.plugin(autoIncrement.plugin, 'Document');
var Document = mongoose.model('Document', DocumentSchema);

一度だけ初期化する必要がありますautoIncrement

于 2015-11-19T17:51:49.790 に答える
2

このコードはMongoDBのマニュアルから引用したもので、実際に _id フィールドを自動インクリメントする方法を説明しています。ただし、どの分野にも応用できます。ドキュメントを挿入した直後に、挿入された値がデータベースに存在するかどうかを確認する必要があります。すでに挿入されている場合は、値を再度インクリメントしてから、もう一度挿入してみてください。このようにして、重複する値を検出し、それらを再インクリメントできます。

while (1) {

    var cursor = targetCollection.find( {}, { f: 1 } ).sort( { f: -1 } ).limit(1);

    var seq = cursor.hasNext() ? cursor.next().f + 1 : 1;

    doc.f = seq;

    targetCollection.insert(doc);

    var err = db.getLastErrorObj();

    if( err && err.code ) {
        if( err.code == 11000 /* dup key */ )
            continue;
        else
            print( "unexpected error inserting data: " + tojson( err ) );
    }

    break;
}

この例では、f は自動インクリメントするドキュメント内のフィールドです。これを機能させるには、インデックスで実行できるフィールドを UNIQUE にする必要があります。

db.myCollection.ensureIndex( { "f": 1 }, { unique: true } )
于 2013-01-22T08:40:09.767 に答える