BeforeSave save pointer

If the user does not have a collection while saving to the nft table, I want to create an automatic collection beforesave and save it to the nft table, but it saves undefined. Where am I going wrong, can you help?

// cloud code

Moralis.Cloud.beforeSave("Nfts", async function(request) {
    const userCollection = request.object.get("collections");
    if (userCollection) {
      logger.info("success");
    } else {
        logger.info("fail");
        const UserCollection = Moralis.Object.extend("UserCollections");
        const collection = new UserCollection();
        collection.set("userId", request.object.get("userId"));
        collection.set("title", "UntitledCollection");
        collection.set("description", "My first collection");
        collection.save(null, { useMasterKey: true }).then((usercollection) => {
           request.object.set("collections",usercollection);
    });
}
  });

// react

const Nfts = Moralis.Object.extend("Nfts");
const nft = new Nfts();
nft.set("category", category);     
nft.set("properties", propertyData);
nft.set("collections", collection); // collection is "" in frontend. i want to set on cloud before save
.......
nft.save().then((nft) => {
	toast.success('Created successfully!',options);
	}, (error) => {
		toast.error('Unsuccessful!',options);
		 alert('Failed to create new object, with error code: ' + error.message);
});

it returns; schema mismatch for Nfts.collections; expected Pointer but got String

Try adding a logger.info of the collection which, so you can verify if you are able to read it through the request.object.get.

1 Like

What are you trying to do here?

You got access to request.user: The Moralis.User that is making the request. This will not be set if there was no logged-in user, and also request.params: The parameters object is sent to the function by the client.
You can try log JSON.stringify(request) to see if you got object property on the returned object.

If the user does not have a collection while creating nft, I want to create an automatic collection just before saving and save this collection as a pointer to the collection field in the nft table.

I can see returned object in logs but saving already done before ‘request.object.set’

Try to use await here, instead of .then, as beforeSave function could finish before that then is executed.

Thank you @cryptokid, it worked the way you said.

1 Like