Merging Documents in PouchDB

I need to retrieve equipment data from pouchdb/couchbase that has users assigned to them. Each piece of equipment has an _id and a checkedOutBy field with the user._id as its value. The employee object contains the user's name. How can I retrieve the equipment objects along with the user names and display them together?

I have tried looking into map/reduce functions that use emit, but I'm struggling to understand the concept. Here is the code snippet I wrote based on what I learned, using AngularJS:

field = "eq::"
this.getAllEquip = function(field){
            function map(doc) {
                if (doc.checkedOutBy !== undefined) {
                    emit(doc.checkedOutBy, {empName : doc.name});
                }
            }
            var result = database.query(map, {include_docs: true,
                            attachments: true,
                            startkey: field,
                            endkey: field + '\uffff'})
                .catch(function (err) {
                //error handling here
            });
            return result
        };

I am unable to see how the two documents are being connected. What am I missing? Why is my result empty?

The equipment JSON structure looks like this:

{checkedOutBy: "us::10015", description: "3P Microsoft Surface w/stylus & power cord", equipId: "SUR1501", purchaseDate: "", rCost: 1000, id:"eq::10001"}

Employee JSON example:

{"firstname":"Joe","gender":"male","lastname":"Blow","status":"active","title":"office","type":"userInfo","_id":"us::10015","_rev":"2-95e9f34784094104ad24bbf2894ae786"}

Thank you for any assistance.

Answer №1

If I have grasped the question correctly, a solution similar to this might be sufficient:

// Example Array of Objects containing Equipment
var equipmentArray = [{checkedOut: "abc1", description: "item1", id: 1},
{checkedOut: "abc2", description: "item2", id: 2},
{checkedOut: "abc3", description: "item3", id: 3},
{checkedOut: "abc1", description: "item1", id: 4},
{checkedOut: "abc4", description: "item3", id: 5},
{checkedOut: "abc6", description: "item3", id: 6}];

// Array of objects representing Employees - the "id" in equipmentArray matches with "checkedOut" in employeesArray  
var employeesArray = [{name: "john", id: "abc1"},
{name: "jack", id: "abc2"},
{name: "alice", id: "abc3"},
{name: "james", id: "abc4"}];

var finalResult = [];  // array for final results

// iterate through equipmentArray
equipmentArray.forEach(function(item) {

var tempObject = item;

var checkedOutId = item.checkedOut;

// using array.find to locate the first element that fulfills the specified function, assuming each employee has a unique ID and there are no duplicates
var foundEmployee = employeesArray.find(function(employee) {

if (employee.id == checkedOutId)

return employee.name

})

// Formulate the object to be included in the final array by adding a new key called "name" based on the outcome of the find operation above 
if (foundEmployee != undefined) {

tempObject.name = foundEmployee.name

}
else {

tempObject.name = "Not found";

}

finalResult.push(tempObject);

})

Answer №2

I want to express my gratitude to Vijay for guiding me towards the PouchDB solution I needed. First step is gathering all the equipment items. Then, following Vijay's technique, looping through the array to add names to objects and create a new array proved to be effective. It was vital to access specific parts of the object such as obj.doc.checkedOutBy and tempObj.doc.name to successfully complete the task.

$pouchDB.getAllDocs('eq::').then(function(udata){
    var result = [];
    // iterating through equipment array 
    udata.rows.forEach(function(obj) {
        var tempObj = obj;
        var checkedout_id=obj.doc.checkedOutBy;

        if (checkedout_id != undefined) {
            $pouchDB.get(checkedout_id).then(function(emp){
                return emp.firstname + " " + emp.lastname
            }).then(function(name){
                tempObj.doc.name = name;
            });
        }
        result.push(tempObj);
    })

Within my service:

this.get = function(documentId) {
    return database.get(documentId);
};

and:

this.getAllDocs = function(field){
    return database.allDocs({
      include_docs: true,
      attachments: true,
      startkey: field,
      endkey: field + '\uffff'});
};

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

What is the best way to extract an integer value from a JSON object?

Currently, I am working on a project using Laravel 5 and have encountered an issue. After running a database query, I received the following response: [{"id":1}] My goal is to extract the value 1 as an integer or string. Any suggestions on how to achie ...

Extrude a face in Three.js along its respective normal vector

My goal is to extrude faces from a THREE.Geometry object, and my step-by-step approach involves: - Specifying the faces to be extruded - Extracting vertices on the outer edges - Creating a THREE.Shape with these vertices - Extruding the shape using THREE.E ...

Preventing the tab key from triggering ng-keypress

Currently, I am utilizing ng-keypress alongside all functionalities enabled by ng-click. However, in Firefox, this configuration leads to unusual behavior when navigating through 'selectable' elements. Is there a way to exclude a specific key wh ...

Node.js: Understanding the issue of a mysterious null value in JSON responses sent to clients

As a beginner in the world of Node.js and JavaScript, I have been struggling to find a solution to my problem even after extensive searching. My current challenge involves sending a JSON object to a Node.js server with an array of 2 elements (longitude an ...

The browser is not showing JavaScript alerts and prompts when they are called inside a function

/*I am attempting to run a color guessing game in my browser, but when I try opening the code in Chrome, it doesn't work. Any suggestions or ideas would be greatly appreciated.*/ var colors = ["Aqua", "Black", "Blue", "Brown", "Coral", " ...

What is the best way to combine duplicate JSON objects together?

I am facing a challenge with my json data structure, shown below: [{ "attributeId": 6, "attributeType": "price", "attributeValue": "{10,20,100}", "displayOn": "true", "attributeName": "price" }, { "attributeId": 6, "attribu ...

What is the best way to incorporate a button in my code that automatically triggers changes at regular intervals?

Is there a way to automatically change the color of my working traffic light in JavaScript on a timed basis, rather than relying solely on button clicks? Here is the current code I am using: <!DOCTYPE html> <html> <head> <style> # ...

Managing a directive in Angular using a service: A guide

I'm currently working on a Service that manages a directive. The main goal is to utilize the Service within a Controller to instruct the Directive to perform certain actions. For example, calling SomeService.tellSomething('ok'); will activ ...

Ensuring no null objects are present in the jQuery each function

In order to iterate through each key value pair in a JSON element and display it, I am encountering an issue where some of the keys have null values. As a result, using $.each is throwing an error: TypeError: obj is null I do not want to remove the null ...

Attempting to utilize the JavascriptExecutor for button testing, however encountering an error message stating 'Unexpected keyword or identifier'

When I look at my code, I see this line: JavascriptExecutor js = (JavascriptExecutor) driver; A red line appears underneath it with the error message Unexpected keyword or identifier I attempted to resolve this by importing org.openqa.selenium.Javascrip ...

Looking for a list of events in Express.js?

I've been searching through the official documentation, but I couldn't find a list of events for express. Does anyone know if there's something like 'route-matched' so that I can use app.on('route-matched', () => {})? ...

Adjusting the X-axis in Highstock: Tips and Tricks

Is there a way to adjust the X axis on this chart? My goal is to shift it so that it only covers half of the width, leaving the other half blank for future plotlines. Any suggestions on how to achieve this? Thanks! :) ...

AngularJS is not responding to a 400 bad request

Despite my efforts to find solutions on Google and Stack Overflow for similar or identical issues, as a newcomer, none of them have provided me with any insight on how to resolve the issues in my code. Here is the script I am working with: $http.post(&ap ...

React Modals: Only the modal component triggered by the first click will open, with no other modals opening

As a newcomer to StackOverflow, I apologize if my problem description is not clear. I am currently learning React and working on a course-search app as a project. The app filters courses based on user input from a JSON file and displays them in cards with ...

Problem encountered with JavaScript getter on iOS 5

While implementing JavaScript getters in my iPad-optimized website, everything was working perfectly until I updated to iOS 5. Suddenly, the site stopped functioning properly. After thorough investigation, I discovered the root cause of the issue. I have ...

Step-by-step guide on incorporating edit, update, and discard functionalities within an Angular Material table component (mat-table)

I am currently working on implementing edit, update, and discard functions in an angular material table. While I have been able to successfully edit and update the table row wise, I am struggling with how to discard table rows. If you would like to see wh ...

What is the best way to retrieve the value of a selected radio button with YUI?

Here is the structure of my radio buttons... <div id="test"> <input name="test1" value="a" type="radio"> <input name="test1" value="b" type="radio"> <input name="test1" value="c" type="radio"> </div> What is the best w ...

I have found that I can load a CSS file using Node Express, however, it seems to be malfunctioning. On the other hand, some

I have added app.use(express.static(path.join(__dirname, 'public'))); to my app.js file. Now I am using bootstrap.css along with my custom CSS file main.css. index.html: ┊ <meta http-equiv="Content-Type" content="text/html; charset=UTF- ...

Promise not being properly returned by io.emit

io.emit('runPython', FutureValue().then(function(value) { console.log(value); //returns 15692 return value; // socket sends: 42["runPython",{}] })); Despite seeing the value 15692 in the console, I am encountering an issue where the promise ...

Troubleshoot: Trouble with selecting the clicked item in AngularJS when using ng-repeat

Is there a way to only delete the selected item from my ng-repeat list instead of deleting all items at once? I can currently delete all items using ng-repeat, but I want to be able to delete just the clicked item. How can I achieve this? https://i.stack. ...