Cloud Function .save() returns undefined

This successfully saves to the database.

return polkamonFirst.save();

But the returned value is always undefined in Moralis logs.

How can the saved object be returned?

Moralis.Cloud.define("saveDamage", function(request) {
    const query = new Moralis.Query("Polkamon");

    query.equalTo("polkamonId", request.params.polkamonId);
  
  	if (request.params.damage <= 0) {
    	return "damage needs to be greater than 0"; 
    }

    query.first()
    .then(function(polkamonFirst) {
        var newHp = polkamonFirst.get("hp") - request.params.damage;

        polkamonFirst.set("hp", newHp);

        return polkamonFirst.save();
    });
});

My server url

https://hld2kn2sv3k3.moralis.io:2053/server

the .save() functions is async, so you might need to add an await on it.

Check this video which explain how to save items on moralis: https://www.youtube.com/watch?v=jgClkiMbWl0&list=PLFPZ8ai7J-iR6DMqBfZwJGc0vaNZPbJDv&index=5

Carlos Z

1 Like

Thank you for your help. :grinning:

Yes the fix required using await instead of then() for async. I also updated the Cloud Function to be async.

Here is my working Cloud Function that returns the saved object.

Moralis.Cloud.define("saveDamage", async (request) => {
    const query = new Moralis.Query("Polkamon");

    query.equalTo("polkamonId", request.params.polkamonId);
  
  	if (request.params.damage <= 0) {
    	return "damage needs to be greater than 0"; 
    }
  
  	const polkamonFirst = await query.first();
  	
    var newHp = polkamonFirst.get("hp") - request.params.damage;

    polkamonFirst.set("hp", newHp);

    const polkamonSave = await polkamonFirst.save();
	return polkamonSave;

});
1 Like