'Incrementing a "PlayerID" with a MongoDB Atlas Trigger
I need to have a playerID
that is separate from _id and increments with each new entry into my users collection. I have tried to follow this tutorial with no luck. My counter collection is called playerIDCounter
and my users collection is simply called users
. I want each user document to have a playerID
field that increments from 1 onwards.
This is my attempt at adapting the tutorial code for my own purpose:
exports = async function(changeEvent) {
const playerID = changeEvent.fullDocument.playerID;
const playerIDCounter = context.services.get("Cluster0").db(changeEvent.ns.db).collection("playerIDCounter");
const users = context.services.get("Cluster0").db(changeEvent.ns.db).collection(changeEvent.ns.coll);
(db.collection)
const counter = await playerIDCounter.findOneAndUpdate({playerID: changeEvent.ns },{$inc: { seq_value: 1 }}, { returnNewDocument: true, upsert : true});
const doc = {};
doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value;
const updateRes = await users.updateOne({playerID: playerID},{ $set: doc});
console.log(`Updated ${JSON.stringify(changeEvent.ns)} with counter ${counter.seq_value} result: ${JSON.stringify(updateRes)}`);
}
I also don't know whether or not I already need to have a playerID
field in the document before it gets passed to this function. If the playerID
field doesn't already exists will it be created and updated automatically? If not, then what placeholder value should playerID
have?
I appreciate anyone who takes the time to help me. I have been stuck for a few days and there aren't too many posts on how to increment values in MongoDB.
Edit: I also don't understand the whole doc[`${changeEvent.ns.coll}.playerID`] = counter.seq_value
bit - what's going on here?
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
Solution | Source |
---|