Code Examples

The following are simple Lua code snippets to Create, Modify, & Remove a Document in Datanet

Create Document:
    * Namespace defaults to 'production'
    * Collection is 'users'
    * Document key is 'Tim'
local collection = Datanet:collection("users");
local username   = "Tim";
local data       = {_id = username,
                    age = 22,
                    hobbies = ["reading", swimming"]
                   };
local ret, err = collection:store(data);
if (err) then
  return ngx.say(err);
end
ngx.say('USER DATA STORED');
        
Modify Document:
    * Namespace defaults to 'production'
    * Collection is 'users'
    * Document key is 'Tim'
    * Actions are to increment Tim's "age" by one (it's his birthday) and add hobby 'sailing'
    * NOTE: for brevity, error checking has been removed
local collection = Datanet:collection("users");
local username   = "Tim";
local doc, err   = collection:fetch(username);
doc:incr("age", 1);
doc:rpush("hobbies", "sailing");
local doc, err   = doc:commit();
ngx.say('HAPPY BIRTHDAY');
        
Remove Document:
    * Namespace defaults to 'production'
    * Collection is 'users'
    * Document key is 'Tim'
local collection = Datanet:collection("users");
local username   = "Tim";
local ok, err    = collection:remove(username);
if (err) then
  return ngx.say(err);
end
ngx.say('USER DATA REMOVED');
        
Extended Documentation
Lua API: Datanet OpenResty API