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).