Populate id field with record data in other collection in LowDB

958 views Asked by At

I'm using LowDB for a small app, in which my db.json has a similar structure to this one:

{
  "clients": [
    {
      "id": "ad839854-a53a-4287-9f94-7e7e3f2b8cab",
      "name": "some name"
    }
  ],
  "jobs": [
    {
      "id": "ad839854-a53a-4287-9f94-7e7e3f2b8cac",
      "type": "fix",
      "client": "ad839854-a53a-4287-9f94-7e7e3f2b8cab"
    }
  ]
}

What I'm trying to achieve is query for all jobs and automatically, populate the client property (using the client id) with it's own data to show in the UI, without persisting it back to the db. I manage to do this with a few lines of javascript:

var vm = this;
vm.jobs = LowDB.get('jobs').value();
var jobClient = null;
angular.forEach(vm.jobs, function (job) {
    if(job.client) {
        jobClient = LowDB.get('clients').find({id: job.client}).value();
        job.client = jobClient;
        console.log(job.client);
    }
});

My question is if is there any built-in/simpler method to achieve the same result with only LowDB or even using lodash? Also it seems that in this way it is persisting the data to the database most likely because of the use of value() but I can't find any other way to achieve this.

Thanks in advance.

1

There are 1 answers

0
pgrodrigues On BEST ANSWER

After carefuly reading LowDB documentation I ended up making a few changes to the code.

First of all I added writeOnChange: false option when requiring lowdb:

var lowdb = require('lowdb')('db.json', {
    writeOnChange: false
});

Then I used cloneDeep() method when querying. Note that LowDB is an angular service that returns lowdb:

vm.job = LowDB.get('jobs').find({id: $routeParams.id}).cloneDeep().value();
vm.clients = LowDB.get('clients').cloneDeep().value();
angular.forEach(vm.jobs, function (job) {
    angular.forEach(vm.clients, function (client) {
        if(client.id === job.client) {
            job.client = client;
        }
    });
});

This way, I achieved the query I wanted and data wasn't persisted to the database anymore. It will only persist after calling:

LowDB.write();