2017-08-04 18 views
0

私はmongoose-sequenceプラグインで見てきましたが、それが唯一の数値形式で保存することができ、カウンタは私のようなユニークなカスタムID(mycustomID)を作成する必要があります0Mongooseのテキストと連結してカウントを増やす方法は?

から開始します:ABCD1001を。 ABCDはプレフィックス値です。私のカウンタは1001から始まります。

私はschema.pre( "save")を使用してこれを実現することを期待していました。私はモンゴに新しいです。誰かがこれを達成する方法に関する情報を提供することはできますか?

は、ここであなたが最後customId取得するように、以下のコマンドを使用してDBから最後に挿入された値を取得することができ、私のスキーマ

var bookSchema = new Schema({ 
    name: { type: String, required: true}, 
    isbn: { type: String}, 
    prefix: {type: String}, 
    mycustomID: {type: String, unique: true}, 
    author: { type: String, required: true}, 
    status: { type: Boolean, default: true }, 
    created_at: Date, 
    updated_at: Date 

}); 

答えて

0

です。 previousCustomId.replace(/^\D+/g, '')を使用してそのカスタムIDを変換し、それを増やすだけです。

bookSchema.find({}).sort({_id:-1}).limit(1, function(err, data) { 
    var previousCustomId = data[0].mycustomID; //Make sure it will return data object or data array 
    var currentCustomId = parseInt(previousCustomId.replace(/^\D+/g, '')) + 1; 

    //Your next entry will be here 

}) 
関連する問題