About MeroDB

MeroDB is a Javascript library that is released under MIT liscense. It helps to manipulate Javascript objects easily like a database. Querying is very similar to NoSQL database. It has the common functions like
  • create
  • insert
  • update
  • delete
  • select
In case of NodeJS, it has frunction to WRITE and READ data into and from a disk.

Installation for NodeJS

Install the library by using following command.

npm install merodb

Create MeroDB Instance

const MeroDB = require("merodb");
var myDb = new MeroDB();

Installation for Browser

Load “merodb.min.js” file which is on dist folder.
<script src="./dist/merodb.min.js"></script>
Create MeroDB Instance

<script>
    document.addEventListener('DOMContentLoaded', function () {
        var myDb = new merodb();
    });
</script>

Look here for SAMPLE. (It works on almost all latest browsers.)

Create collection

create - <collection name>, <is activate>? @returns: boolean
MeroDB can hold multiple collection. As like a "Table" in RDBMS first create COLLECTION. The first parameter is name of collection.It should be of string type.
parameter type description
collection name string name of collection ot be created. Similar to "Table" in RDBMS.
is activate boolean (optional) will activate the collection if set to true
The second parameter is optional and can be omitted. "createCollection" will return false if failed, Otherwise returns true.

var isCreated = myDb.createCollection("continent");
if(isCreated === false){
    console.log("Failed to create collection");
}
It has a method called getCollections which will return the list of collections found in a database.

var myCollections = myDb.getCollections();

Insert Data

insert - <collection name>?, <data> @returns: boolean
parameter type description
collection name string(optional) it can be omitted for active collection
data object it is the data to be inserted which is called document

Insert Single Document


var data1 = {id:1,place:"Asia",color:"red"};
var data2 = {id:3,place:"Europe",color:"green"};
var collectionName = "continent";
myDb.insert(collectionName,data1);
myDb.insert(collectionName,data2);
However, first parameter can be omitted if a collection is activated. To activate a collection "use" method is executed.

myDb.use("continent");
var data1 = {id:5,place:"Africa",color:"blue"};
var data2 = {id:7,place:"America",color:"yellow"};
myDb.insert(data1);
myDb.insert(data2);
"use" & "insert" methods will return false if failed, Otherwise returns true. if second parameter is passed as true while creating collection, it will automatically activate the given collection.

myDb.createCollection("continent", true);
myDb.insert({id:7,place:"Antartica",color:"pink"});

Insert Existing Object

loadFromJsonObject - <collection name>?, <data> @returns: boolean
It will create a collection named user and inserts data of myObj.

var myObj = [
                {
                    "userId": 1,
                    "id": 1,
                    "title": "delectus aut autem",
                    "completed": false
                },
                {
                    "userId": 1,
                    "id": 2,
                    "title": "quis ut nam facilis et officia qui",
                    "completed": false
                },
                {
                    "userId": 1,
                    "id": 3,
                    "title": "fugiat veniam minus",
                    "completed": false
                },
                {
                    "userId": 1,
                    "id": 4,
                    "title": "et porro tempora",
                }
            ];
myDb.loadFromJsonObject("user", myObj);

Search Data

find - <collection name>?, <condition>, <column headers>? @returns: boolean
parameter type description
object (1 param) search condition returns all the document satisfiying this condition
object, array(2 params) search condition, column list similar to case 1 but only the columns listed will be returned
string, object, array(3 params) collection name, search condition, column list name of collection can be explicitly applied

var searchTableString = "user";
var searchConditionObject = { place: "Asia" };
var resultColumnArray = ["id"];

var searchResult = myDb.find(searchTableString, searchConditionObject);
var searchResult = myDb.find(searchTableString, searchConditionObject, resultColumnArray);
var searchResult = myDb.find(searchConditionObject);
var searchResult = myDb.find(searchConditionObject, resultColumnArray);

Search Condition

name meaning usage
$e equals { id: { $e: 200 } }
$ne not equal { id: { $ne: 200 } }
$lt less then { id: { $lt: 200 } }
$lte less then or equal { id: { $lte: 200 } }
$gt greater then { id: { $gt: 200 } }
$gte greater then or equal { id: { $gte: 200 } }
$bt between { id: [2, 5] }
$cont contains { name: { $cont: "a" } }

Uses-1


var searchResult = myDb.find("user",{ id: { $gte: 4 } });

Uses-2


var searchResult = myDb.find("user", {
        $or: [{ id: 1 }, { name: "kk" }],
        salary: 15
    });

Uses-3


var searchResult = myDb.find({
        $or: [
            { isbn: { $gte: 2000 } },
            { writer: { $ne: "df" } }
        ],
        name: { $ne: "df" },
        price:{$lt:5000}
    });

Update Data

update - <collection name>?, <condition>, <new value> @returns: boolean
paramet type description
collection name string it can be omitted for active collection
condition object documents fulfilling this condition will be updated with new value
new value object this value will be the new value

※ Note

if the does not contain "$set" key then all the the data of the document fulfilling given condition will be replaced with the object.


// create instance of MeroDB
var myDb = new MeroDB();
// create collection with name "user" and activate
myDb.createCollection("user", true);
// insert two documents in the active collection
myDb.insert({ id: 1, name: "hbeauty", enroll: "2018-01-20", sex: "M", salary: 15 });
myDb.insert({ id: 2, name: "dakc", enroll: "2017-02-28", sex: "F", salary: 35 });
// update active collection having its documents id = 2
myDb.update({ id: 2 }, { id: 1111, name: "tom" });

// get current data from active collection
var newData = myDb.find({});
console.log(newData[0], newData[1]);
// Object {id: 1, name: "hbeauty", enroll: "2018-01-20", sex: "M", salary: 15}
// Object {name: "tom"}
// the result will be as following where second document is completely replaced.
If contains "$set" key then it will update the the keys set.

// update active collection having its documents id = 2
myDb.update({ id: 2 }, { $set: { id: 1111, name: "tom" } });

// get current data from active collection
var newData = myDb.find({});
console.log(newData[0], newData[1]);
//Object {id: 1, name: "hbeauty", enroll: "2018-01-20", sex: "M", salary: 15}
//Object {id: 1111, name: "tom", enroll: "2017-02-28", sex: "F", salary: 35}
// only id,name were updated.
Condition is object which is exactly similar to the condition for find method. Search Condition

Uses 1


var searchCondition = { id: { $lt: 2 } };
var newData = { $set: { name: "harilarl" } };
myDb.update(searchCondition, newData);

// Get number of documents updated
var updatedNumber = myDb.collAffected();
console.log("number of updated documents is " + updatedNumber);

Delete Data

delete - <collection name>?, <condition> @returns: boolean

Uses 1

Delete from user where id is less then two.

var searchCondition = { id: { $lt: 2 } };
var documentName = "user"
var isDelete = myDb.delete(documentName, searchCondition);
if (isDelete == true) {
    console.log("Deleted.");
}

// Get number of documents deleted
var deletedNumber = myDb.collAffected();
console.log("number of deleted documents is " + deletedNumber);

Get Document Count

getDocumentCount - <collection name>? @returns: string
It will return the number of documents existing on given collection name. If no collection name is specified then it will return the active collection's row number.

// get document count for "user" collection
var collectionName = "user";
var numberRows = myDb.getDocumentCount(collectionName);

// get active collection's document count
var numberRowsActiveCollection =  myDb.getDocumentCount();

Get Affected Document Number

getDocumentNumAffected - @returns: number
It will return number of documents in a collection affected after update or delete process.

// delete from collection user
var searchCondition = { id: { $lt: 2 } };
var collectionName = "user"
var isDelete = myDb.delete(documentName, searchCondition);
// get the number of documents deleted
var numberRowsDeleted = myDb.getDocumentNumAffected();

Get Active Collection

getActiveCollection - @returns: string
It will return the name of active collection if exist.

// get name of active collection
var activeCollection = myDb.getActiveCollection();

Get Error

getError - @returns: string
It will return error content.

// get the error message
var errorMessage = myDb.getError();

Get Collection List

getCollections - @returns: object
It will return all the collections as array.

// get the names of collections existing in a database
var arrayCollection = myDb.getCollections();

Load From Json Object

loadFromJsonObject - <collection name>, <data> @returns: boolean
parameter type description
collection name string name of collection to hold data
data array of json object data to be loaded in a database
It will load the json data into a database.

// create data to be inserted
let userData = [];
userData.push({ id: 1, name: "pk", salary: 10 });
userData.push({ id: 2, name: "ck", age: 20, salary: 20, sex: "M" });
userData.push({ id: 3, name: "dk", create: "2018-01-20", sex: "M", salary: 35 });
userData.push({ id: 4, name: "kk", salary: 25, sex: "M" });
userData.push({ id: 5, name: "kk", salary: 15 });
// load to database with collection name user
myDb.loadFromJsonObject("user", userData);

Save Data Explicit

save - <file path> @returns: boolean
It will output the contents of database to given file.This method only works for nodejs environment.

// write contents to "my.db"
myDb.save("./my.db");

Save Data Implicit

updateAlways - <file path> @returns: nothing
It will output the contents of database on each insert,update,delete action(no need to call save method). This method only works for nodejs environment.

// write contents to "my.db" on each change
myDb.updateAlways("./my.db");

Load From File

loadFromFile - <file path> @returns: boolean
It will load the data from file This method only works for nodejs environment.

// load from file
myDb.loadFromFile("./my.db");