I define a filed: myid in class _User. and the myid is self-incrementing. how to do ?
I use k8s, run 2 pod of parse-server.
I use hook user in beforeSave.
if(req.object.isNew){
const query = new Parse.Query(Parse.User);
query.addDescending("createdAt");
const result = await query.first({useMasterKey: true});
//logInfo(result);
let myid = 1000;
if (result?.get("myid")) {
myid = result.get("myid") + 1;
}
req.object.set("myid", myid);}
But there are duplicate myid users
Firstly you should solve race condition problems on your system.
i solved.
export async function getNextMyId() {
return await getNextValue("_User", "myid");
}
async function getNextValue(className, fieldName) {
const query = new Parse.Query("Counter");
query.equalTo("class_Name", className)
query.equalTo("field_Name", fieldName);
try {
const counter = await query.first({useMasterKey: true});
if (counter) {
counter.increment("value");
await counter.save(null, {useMasterKey: true});
return counter.get("value");
}
throw new Parse.Error(-1, `get ${fieldName} failed`)
} catch (e) {
throw new Parse.Error(-1, `get ${fieldName} failed`)
}
}