How can I save a datastore

1: I am trying to save a whole folder and the folders inside that folder (the second folders have values)

2: I have looked on hidden developers, other forum posts, etc but I still cant understand how to put it in.

local DataStoreService = game:GetService("DataStoreService")
local MyDataStoreService = DataStoreService:GetDataStore("MyDataStore")


game.Players.PlayerAdded:connect(function(player)
local leaderstats = Instance.new("Folder")
leaderstats.Name = "leaderstats"
leaderstats.Parent = player

local Money = Instance.new("IntValue")
Money.Name = "Money"
Money.Parent = leaderstats
Money.Value = 25000
	
local Level = Instance.new("IntValue")
Level.Name = "Level"
Level.Parent = leaderstats
	
local PS = Instance.new("Folder")
PS.Name = "PlayerStats"
PS.Parent = player
	
local Owned = Instance.new("IntValue")
Owned.Name = "Owned"
Owned.Parent = PS
	
local BName = Instance.new("StringValue")
BName.Name = "BName"
BName.Parent = PS	
	
local Started = Instance.new("BoolValue")
Started.Name = "Started"
Started.Parent = PS
	
local Properties = Instance.new("Folder")
Properties.Name = "Properties"
Properties.Parent = player


local playerUserId = "Player_"..player.UserId

local data
local success, errormessage = pcall(function()
data = MyDataStoreService:GetAsync(playerUserId)
end)

	if success then
		if data then
			Money.Value = data.Money
			Level.Value = data.Level
			Owned.Value = data.Owned
			player.PlayerStats["BName"].Value = data.BName
			Started.Value = data.Started

			
end
end
end)

while wait(30) do
	for i,v in pairs (game.Players:GetPlayers()) do
		local player = v
		local playerUserId = "Player_"..player.UserId

		local data = {
			Money = player.leaderstats.Money.Value;
			Level = player.leaderstats.Level.Value;
			Owned = player.PlayerStats.Owned.Value;
			BName = player.PlayerStats.BName.Value;
			Started = player.PlayerStats.Started.Value;
			

		}

		local success, errormessage = pcall(function()
			MyDataStoreService:SetAsync(playerUserId, data)
		end)

		if success then
			print("Data Saved Success!")
		else
			print ("There was an error!")
			warn(errormessage)
		end
	end
end

Please do not ask people to write entire scripts or design entire systems for you. If you can’t answer the three questions above, you should probably pick a different category.

Maybe try making different while wait(30) loops, one for the leaderstats folder and another for the playerstats folder.

I preffer you to use tables

if you want a tutorial here it is:

And make sure this is enabled in your game:

( Home > Game Settings > Security )

image