How can I delete codes from the datastore?

Hi.

I have written this script which basically when you click a button to create a server, it fires a remote event and then that remote event creates a server code so that other players that enter it in a text box can use it. The only problem is that once everyone leaves that server the code doesn’t delete from the datastore, and I was looking for some guidance on how to do that.

The code:

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Players = game:GetService("Players")
local DataStoreService = game:GetService("DataStoreService")
local TeleportService = game:GetService("TeleportService")

local RemotesFolder = ReplicatedStorage:WaitForChild("Remotes")
local CreateServer = RemotesFolder:WaitForChild("CreateServer")
local TextBoxCode = RemotesFolder:WaitForChild("TextBoxCode")
local SendCode = RemotesFolder:WaitForChild("SendCode")

local serverDataStore = DataStoreService:GetDataStore("ServerDatastores")
local serverId = 10715581299

local function GenerateUniqueShortCode()
	local characters = "ABCDEFGHIJKLMNOPQRSTUVWXYZabcdefghijklmnopqrstuvwxyz0123456789"
	local length = 5
	local maxAttempts = 10
	local attempt = 1

	while attempt <= maxAttempts do
		local code = ""

		for _ = 1, length do
			local index = math.random(1, #characters)
			code = code .. characters:sub(index, index)
		end


		local serverData = serverDataStore:GetAsync(code)
		if not serverData then
			return code 
		end

		attempt = attempt + 1
	end
	return nil 
end

local function UpdateServerData(serverCode, serverId, shortCode, player)
	local serverData = serverDataStore:GetAsync(serverCode) or {}
	table.insert(serverData, { server = serverId, player = player.UserId, serverCode = shortCode })
	serverDataStore:SetAsync(serverCode, serverData)
end

local function CreateAndVerifyServer(player)
	local serverCode = TeleportService:ReserveServer(serverId)

	local shortCode = GenerateUniqueShortCode()

	if not shortCode then
		SendCode:FireClient(player, "Unable to update server data. Unique code could not be generated. The probability of this error is 62^5!")
		return
	end

	SendCode:FireClient(player, "Teleporting to your destination...")
	UpdateServerData(shortCode, serverCode, shortCode, player)

	local UserId = player.UserId

	local data = {
		code = shortCode,
		playerId = UserId
	}


	TeleportService:TeleportToPrivateServer(serverId, serverCode, {player}, "Spawn", data)
end

local function TeleportToServerByCode(player, code)
	local plr = Players:GetPlayerByUserId(player.UserId)

	if plr then
		local serverData = serverDataStore:GetAsync(code)
		if serverData then
			local serverInfo = serverData[1]
			if serverInfo then
				local serverNumber = serverInfo.server
				TextBoxCode:FireClient(player , "Code valid, teleporting...")

				local success, errorMsg = pcall(function()
					TeleportService:TeleportToPrivateServer(serverId, serverNumber, { plr })
				end)

				if not success then
					warn('Could not load server data, with error ' .. errorMsg)
				end
			end
		end
	end
end


CreateServer.OnServerEvent:Connect(CreateAndVerifyServer)
TextBoxCode.OnServerEvent:Connect(TeleportToServerByCode)

Any help would be appreciated, thanks!

You would use dataStore:RemoveAsync() to remove a key from the datastore.

Thanks, but everytime i try to print the serverdata, it prints out as nil even though the code for the datastore is correct, I don’t know what I am doing wrong. (this code is placed in the reserved server):

local DataStoreService = game:GetService("DataStoreService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Remote = ReplicatedStorage:WaitForChild("ServerCode")
local DataStore = DataStoreService:GetDataStore("Data")



local serverData 

Remote.OnServerEvent:Connect(function(player, code)
	serverData = DataStore:GetAsync(code)
	print(serverData)
	if serverData then
		local serverInfo = serverData[1]
		print(serverInfo)
	end
end)



local function onGameClose()
	if serverData then
		local serverInfo = serverData[1]
		
		if serverInfo then
			local success, err = pcall(function()
				DataStore:RemoveAsync(serverInfo)
			end)
		end
	end
end


game:BindToClose(onGameClose)

Nevermind, I was sending data incorrectly, but when i run the function the serverinfo doesn’t delete:

local DataStoreService = game:GetService("DataStoreService")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local Remote = ReplicatedStorage:WaitForChild("ServerCode")
local DataStore = DataStoreService:GetDataStore("Data")

local TeleportService = game:GetService("TeleportService")
local serverData




Remote.OnServerEvent:Connect(function(player, code)
	serverData = DataStore:GetAsync(code)
	if serverData then
		local serverInfo = serverData[1]
		for i, val in pairs(serverInfo) do
			print(val)
		end
	end
end)



local function onGameClose()
	if serverData then
		local serverInfo = serverData[1]
		
		if serverInfo then
			local success, err = pcall(function()
				DataStore:RemoveAsync(serverInfo)
			end)
		end
	end
end


game:BindToClose(onGameClose)

With a few modifications I have managed to make the data delete, but when there is more than 1 person in the server and they leave for some reason the data does not delete:

Client code:

local Players = game:GetService("Players")
local ReplicatedStorage = game:GetService("ReplicatedStorage")
local TeleportService = game:GetService("TeleportService")

local LocalPlayer = Players.LocalPlayer
local PlayerGui = LocalPlayer.PlayerGui
local TeleportData = TeleportService:GetLocalPlayerTeleportData()
local Remote = ReplicatedStorage:WaitForChild("ServerCode")

local ServerCode 
local OwnerUserId 

if TeleportData then
	ServerCode = TeleportData.code
	OwnerUserId = TeleportData.playerId
end

local ServerCodeGui = PlayerGui:WaitForChild("ServerCode")
local Frame = ServerCodeGui.ServerCodeFrame
local TextBox = Frame.ServerCode

if LocalPlayer.UserId == OwnerUserId then
	Frame.Visible = true
	TextBox.Text = TeleportData.code
	Remote:FireServer(ServerCode)
	print("Fired!")
end

Server code:

local DataStoreService = game:GetService("DataStoreService")
local Players = game:GetService("Players")

local ReplicatedStorage = game:GetService("ReplicatedStorage")
local RunService = game:GetService("RunService")

local serverData
local ServerCode

local DataStore = DataStoreService:GetDataStore("ServerStores")
local Remote = ReplicatedStorage:WaitForChild("ServerCode")


Remote.OnServerEvent:Connect(function(player, code)
	ServerCode = code
	serverData = DataStore:GetAsync(code)
end)


local function onGameClose(code)
	if serverData then
		local serverInfo = serverData[1]
		if serverInfo then
			local success, err = pcall(function()
				DataStore:RemoveAsync(code)
			end)
		end
	end
end

if not RunService:IsStudio() then
	game:BindToClose(function()
		if #Players:GetPlayers() <= 1 then return end
		onGameClose(ServerCode)
	end)
end