Hello. I am trying to implementing a playerID field - separate from _id - that auto increments from 1 onward with each new entry into my users collection. I have read and am trying to follow this tutorial but I’m not having any luck. I simply don’t understand the example code and I’m fairly new with MongoDB as well.
I have two collections: “users” and “playerIDCounter”. I would like to adapt the example code from the tutorial for these two collections and to increment on the playerID field rather than the _id field. So far I have not been able to get this to work.
The example code is:
exports = async function(changeEvent) {
var docId = changeEvent.fullDocument._id;
const countercollection = context.services.get("<ATLAS-CLUSTER>").db(changeEvent.ns.db).collection("counters");
const studentcollection = context.services.get("<ATLAS-CLUSTER>").db(changeEvent.ns.db).collection(changeEvent.ns.coll);
var counter = await countercollection.findOneAndUpdate({_id: changeEvent.ns },{ $inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});
var updateRes = await studentcollection.updateOne({_id : docId},{ $set : {studentId : counter.seq_value}});
console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result : ${JSON.stringify(updateRes)}`);
};
I would appreciate anyone that can explain what’s actually going on here.