Examples

Examples

Production-ready real-world implementation examples

All examples use async operations with callbacks to prevent server lag. These are production-ready patterns you can use directly in your server!

Available Examples

Player System

Complete player data management with async load/save

Inventory System

Non-blocking item management and storage

Leaderboard

Real-time rankings with async aggregation

Shop System

Transactional purchases with error handling

Event Logger

High-volume event tracking without lag

Quick Start Template

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)

Key Patterns Used

Error-First Callbacks

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)

Chained Operations

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)

Error Handling

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!