How to loop through all Datastores & access the data

Info: I am creating an experience in which players can place objects which will be saved using Datastore2, and loaded in every server. So basically permanent parts.

Issue: I can’t seem to correctly code the loading.

I have tried ListDataStoresAsync() and ListKeysAsync(), I don’t think I’m correctly utilizing them however.

My code for loading all data stores and accessing the data in each one:

	local Success, PaperStore = pcall(function()
		local Datastores = DatastoreService:ListDataStoresAsync()
		for item, pageNo in iterPageItems(Datastores) do
			print(item.DataStoreName)
			local Options = Instance.new("DataStoreOptions")
			Options.AllScopes = true
			return DatastoreService:GetDataStore(item.DataStoreName, "", Options)
		end
	end)
	
	if Success then
		print("Loaded Datastores!")
		
		local Success, Keys = pcall(function()
			local Keys = {}
			for DatastoreInstance, Key in iterPageItems(PaperStore:ListKeysAsync()) do
				table.insert(Keys, Key)
			end
			return Keys
		end)
		if Success and Keys then
			print("Loaded Keys!")
			
			local CurrentKey = math.max(unpack(Keys))
			print(CurrentKey)
			local PaperData = PaperStore:GetAsync(CurrentKey)
			print(PaperData)
		else
			warn("Error!")
		end
	else
		warn("Error!")
	end

I currently get this error:

image
Reminder: This is what the data looks like in Datastore Editor Plugin, I don’t know if this helps.

image
image

Datastore2 uses OrderedDataStore to list all the keys, which is what is shown in the last image. To get the last key, you just need to use OrderedDataStore in descending order, and get the first value. The first value is the latest key you need to access the main data.

However, I’m not sure why you aren’t just letting DS2 handle it. DS2 already has data loading functionality.

I figured it out, if anyone’s wondering.

	local Success, Data = pcall(function()
		local Global = {}
		local Datastores = DatastoreService:ListDataStoresAsync("", 10)
		for Data, Index in iterPageItems(Datastores) do
			local Datastore = DatastoreService:GetDataStore(Data.DataStoreName)
			local Keys = Datastore:ListKeysAsync("", 10, "", true)
			for KeyObject, Index in iterPageItems(Keys) do
				local StoreData = Datastore:GetAsync(KeyObject.KeyName)
				print(Data.DataStoreName, StoreData)
				table.insert(Global, StoreData)
			end
		end

		return Global
	end)

This topic was automatically closed 14 days after the last reply. New replies are no longer allowed.