node.jsparse-platformparse-cloud-codeback4app

How to set Custom object Id through could code Parse.com


I'm using Parse server 3.10 which is hosted by Back4app. I've enabled the option to allow custom Id in the server custom settings, {"allowCustomObjectId": true}, and now i'm able to set the custom Id of an object through an API call like this.

-H "X-Parse-Application-Id: APPLICATIONID"
-H "X-Parse-REST-API-Key: REST_KEY" 
--data-urlencode "{"objectId":"xWMyZ4YEGZ","name":"Nat"}" 
https://parseapi.back4app.com/classes/Test

But I need to set it through cloud code , right now i'm trying to do something like this but this is not working.

Parse.Cloud.define("setId",async (request) => { 
        const GameScore = Parse.Object.extend("GameScore");
        const gameScore = new GameScore();

        gameScore.set("objectId", "8YgwDJ19qX");
        gameScore.set("name","nat");
        return await gameScore.save(null,{useMasterKey:true});
});

When I try to run this cloud function this is the error that I get.

{
    "code": 101,
    "error": "Object not found."
}

Looking forward to solutions.


Solution

  • It seems at this current time it is not possible to set custom ID through cloud code using JavaScript. A workaround for this is using REST API through cloud code like so:

    Parse.Cloud.define("createObjectId", async (request) => {
        //Your custom id
        const objectId = "8YgwDJ18qX";
        //Your Class name and another optional class variable
        const { nameClass, propertyName } = request.params;
        //Make sure to define these environment variables in your server's env file
        const { APPLICATION_ID,  REST_KEY, SERVER_URL } = process.env;
        //Finally call hit the api.
        return Parse.Cloud.httpRequest({
            method: 'POST',
            url: `${SERVER_URL}/classes/${nameClass}`,
            headers: {
                'Content-Type': 'application/json;charset=utf-8',
                'X-Parse-Application-Id':APPLICATION_ID,
                'X-Parse-REST-API-Key':REST_KEY
            },
            body: {
                objectId: objectId,
                name: propertyName
            }
        });
    });