Zaid
Zaid

Reputation: 79

How to store node.js object from npm package in mongodb

I am beginner in nodejs. I am using merkle-tools in my meteor application. I am creating an object of class MerkleTools.

var merkleObj = new MerkleTools();

Is this possible to store this object merkleObj in MongoDB? So at require time, I can retrieve the stored object from DB and call its function like addLeaf() etc.

Upvotes: 2

Views: 88

Answers (1)

Cedomir Rackov
Cedomir Rackov

Reputation: 1092

The tree has to be serialized before you store it in a database. Library you are using doesn't have such an option but you can easily do it yourself.

The following code assumes you are using this module https://www.npmjs.com/package/merkle-tools

Serialize function:

const serializeTree = (tree) => {
  const len = tree.getLeafCount();
  const serialized = [];

  for (let i = 0; i < len; i++) {
    // If you want to save binary data remove .toString('hex');
    serialized.push(tree.getLeaf(i).toString('hex'));
  }

  return serialized;
}

You get an array that you can easily store in a database.

When restoring the tree from the database you can do the following:

const makeTree = (serialized) => {
  const len = serialized.length;
  const tree = new MerkleTools();

  for (let i = 0; i < len; i++) {
    tree.addLeaf(serialized[i]);
  }

  tree.makeTree();

  return tree;
}

Returned value from the makeTree function is a merkleTools tree so you can use the methods like .addLeaf() to it.

Upvotes: 3

Related Questions