0

I´m trying to generate an autoincremental value in an Schema using Mongoose with MongoDB in a NestJS project.

The idea is the to replicate this (from here Mongoose auto increment) but with Nest.

var entitySchema = mongoose.Schema({
  testvalue:{type:String,default:function getNextSequence() {
        console.log('what is this:',mongoose);//this is mongoose
        var ret = db.counters.findAndModify({
                 query: { _id:'entityId' },
                 update: { $inc: { seq: 1 } },
                 new: true
               }
        );
        return ret.seq;
      }
    }
});

I was rewriting this in the following wayÑ

UserSchema.pre<User>('save', async function (next: any) {
  const userModel = new Model<UserDocument>();
  const last = await userModel.findOne({}).sort({ _id: -1 }).exec();
  this.number = last.number ? last.number + 1 : 1;
  next();
});

The issue that I found is that the presave code is not being executed, and also I have some doubts about the instance of Model that I´m not sure it will work in that way (or if it is the right way to do it).

Faabass
  • 1,394
  • 8
  • 29
  • 58
  • I think you are missing the point of the original implementation in mongoose. They employ atomicity of mongodb updates on document level, which guarantees accurate math even on high volume of concurrent requests. Your solution, even if you make it working, can result with 2 users having the same number, if 2 requests are executed at the same time. – Alex Blex Jul 22 '22 at 12:37
  • @AlexBlex do you have any suggestion about how to mantain an incremental value (It's for a transaction number, not for an ID) – Faabass Jul 22 '22 at 13:14
  • If `$inc` used in mongoose works for you - go for it. – Alex Blex Jul 22 '22 at 13:17
  • Nop.. that doesn't work for me as it's incremente the previous value of the document. I guess the only option is to use a trigger in the database – Faabass Jul 22 '22 at 17:47
  • hmm, isn't `this.number = last.number ? last.number + 1 : 1;` supposed to increment previous value? Anyway, it' up to you, not related to the question itself. I would only mention that triggers are Atlas specific offering, not a mongodb feature. Besides, triggers can be executed simultaneously too. They suffer from the same issue of concurrent updates. – Alex Blex Jul 22 '22 at 18:03
  • well as I was not using Atlas, I change my mind of using incremental values for user friendly identifiers to random string code – Faabass Jul 23 '22 at 18:04

0 Answers0