1

We'd love to have an integer autoincrement field within a Mongo Db document / "table", possibly being different from the autogenerated and unique _id index.

The purpose is to provide the users with a unique readable number, auto-incrementing itself, to be used as a reference for the logical entity associated with the database table we are using. The users will refer to that number for example to identify a printed document associated to that entity.

The expected behavior would be to have that number automatically incremented within the database table itself, exactly like it happens in different kinds of databases.

We have implemented our project with the combo: Vue JS - Node - Mongo db. The aim would be to avoid using some JS "trick" to physically increment the number, while having this action done directly in the model of the document.

We couldn't find anything like that in the official documentation, could someone please help us with this? Thanks so much in advance.

frandro93
  • 13
  • 1
  • 4

2 Answers2

2

MongoDB does not have an auto increment functionality(In built). Need to write extra logic to do that.

You could solve this by keeping track the 'id' in a separate collection called 'user_sequence' and store a custom function in MongoDB to get the next value.

Take a look at: https://docs.mongodb.com/manual/tutorial/store-javascript-function-on-server/

Create a query like:

db.users.insert({
    userid: sequenceNextValue("userid")
})

Step by step tutorial by MongoDB: https://docs.mongodb.com/v3.0/tutorial/create-an-auto-incrementing-field/

REF:- mongodb second id field with auto increment

WAY - 2

if you like to use Mongoose (node lib). Following code will help you

var CounterSchema = Schema({
    _id: {type: String, required: true},
    seq: { type: Number, default: 0 }
});
var counter = mongoose.model('counter', CounterSchema);

var entitySchema = mongoose.Schema({
    testvalue: {type: String}
});

entitySchema.pre('save', function(next) {
    var doc = this;
    counter.findByIdAndUpdate({_id: 'entityId'}, {$inc: { seq: 1} }, function(error, counter)   {
        if(error)
            return next(error);
        doc.testvalue = counter.seq;
        next();
    });
});
0

In my case $inc not worked because i used $inc inside $set :(

for example

await userSchema.updateOne({ _id: mongoose.Types.ObjectId(req.userId) }, { $set: { $inc: { myBalance: -claimAmount } } });

instead of

await userSchema.updateOne({ _id: mongoose.Types.ObjectId(req.userId) }, { $inc: { myBalance: -claimAmount }});
MUHAMMAD SHAHID RAFI C P
  • 1,067
  • 1
  • 12
  • 25