All examples use async operations with callbacks to prevent server lag. These are production-ready patterns you can use directly in your server!
require("mongo")
-- Setup connection
local client = MongoDB.Client("mongodb://localhost:27017")
local db = client:Database("gameserver")
local collection = db:Collection("your_collection")
-- Create indexes (sync is fine for initialization)
collection:CreateIndex({ steamid = 1 }, true, "steamid_unique")
-- Example: Async player load
hook.Add("PlayerInitialSpawn", "LoadPlayer", function(ply)
collection:FindOneAsync({
steamid = ply:SteamID()
}, function(err, data)
if err then
ErrorNoHalt("Database error: " .. err .. "\n")
return
end
if data then
-- Load existing player
print("Loaded player:", ply:Nick())
else
-- Create new player
collection:InsertOneAsync({
steamid = ply:SteamID(),
name = ply:Nick(),
joined = os.time()
})
end
end)
end)
-- Example: Async player save
hook.Add("PlayerDisconnected", "SavePlayer", function(ply)
collection:UpdateOneAsync(
{ steamid = ply:SteamID() },
{ ["$set"] = { last_seen = os.time() } },
true, -- upsert
function(err, count)
if not err then
print("Saved player:", ply:Nick())
end
end
)
end)
All async operations use Node.js-style error-first callbacks:
collection:FindOneAsync(filter, function(err, result)
if err then
-- Handle error
return
end
-- Handle success
end)
Multiple async operations can be chained:
collection:FindOneAsync(filter, function(err, doc)
if err or not doc then return end
-- Next operation based on first result
collection:UpdateOneAsync(
{ _id = doc._id },
{ ["$set"] = { processed = true } },
false,
function(err, count)
-- Handle update result
end
)
end)
Proper error handling prevents data loss:
function SafeUpdate(steamid, data, callback)
collection:UpdateOneAsync(
{ steamid = steamid },
{ ["$set"] = data },
false,
function(err, count)
if err then
ErrorNoHalt("Update failed: " .. err .. "\n")
if callback then callback(false) end
return
end
if callback then callback(true) end
end
)
end
New to async operations? Read the Async Operations Guide first!