PouchDB - Invoking get() within a function results in a TypeError: cb is not a function

I'm in the process of creating a basic login system using PouchDB, but I've encountered an issue when attempting to execute db.get() within my logIn() function.

  var submit = $("input[name='submit']");

function logIn() {
    var username = $("input[name='username']").value;
    var password = $("input[name='password']").value;

    db.get(table.users, (err, info) => { // <-- Pouch db get() function to retrieve data
        if (!err) {
            var data = ("db value", info);
            for (i = 0; i < 2; i++) {
                if (username == data[i].name && password == data[i].pass) {
                    console.log(username + " is logged in!");
                    return;
                }
            }
            console.log("Incorrect data!");
        } else {
            console.log("err field", err);
        }
    });
    db.get(); // <-- Calling get() function here
}
  
submit.click(() => {
    logIn(); // <-- Triggering login() function on click
});

The error message seen in the console reads:

Uncaught (in promise) TypeError: cb is not a function

Is there a more efficient approach to handle this situation?

Answer №1

An issue has arisen

Uncaught (in promise) TypeError: cb is not a function

The error occurs in db.get() because the method is being called without a callback parameter (no parameters at all).

In the logIn method, there are two calls to db.get, first one here

db.get(table.users, (err, info) => { // <-- Pouch db get() function to access data
 ...
});

and the second call happens here

db.get(); // <-- Here I attempt another get() function call

The second call fails immediately because it seems like

db.get(table.users,(err,info) =>
is defining db.get but it's actually an executed call.

Below you can see an example of db.get with a callback. An async/await example is also included. Refer to the pouchDB documentation for get

const g_result = 'result';
const gel = id => document.getElementById(id);
let db;

function logIn(userName, password) {
  const view = gel(g_result);
  // Retrieve the Users doc using get
  db.get("Users", (err, doc) => {
    if (err) {
      view.innerText = JSON.stringify(err, undefined, 3);
    } else {
      let info = doc.data.find(e => e.name === userName && e.pass === password);
      if (info) {
        view.innerText = `👍 Welcome ${userName}!`;
      } else {
        view.innerText = `👎 Log in failed, try again.`;
      }
    }
  });
}

async function logInAwait(userName, password) {
  const view = gel(g_result);
  
  let text = "";
  try {
    let doc = await db.get("Users");
    let info = doc.data.find(e => e.name === userName && e.pass === password);
    if (info) {
      text = `👍 Welcome ${userName}!`;
    } else {
      text = `👎 Log in failed, try again.`;
    }
  } catch (err) {
    text = JSON.stringify(err, undefined, 3);
  } finally {
    view.innerText = text;
  }

}

// Sample documents
function getDocsToInstall() {
  return [{
    _id: "Users",
    data: [{
        name: "Jerry",
        pass: "Garcia"
      },
      {
        name: "Bob",
        pass: "Weir"
      },
      {
        name: "Wavy",
        pass: "Gravy"
      },
    ]
  }];
}

// Initialize database instance
async function initDb() {
  db = new PouchDB('test', {
    adapter: 'memory'
  });

  await db.bulkDocs(getDocsToInstall());
};

(async() => {
  await initDb();
  gel("form").style = "";
})();
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb-7.1.1.min.js"></script>
<script src="https://github.com/pouchdb/pouchdb/releases/download/7.1.1/pouchdb.memory.min.js"></script>
<pre id="form" style="display: none">
<label for="user">User Name</label>
<input id="user" /> 
<label for="pass">Password</label>
<input id="pass" /> <br/>
<button onclick="logIn(gel('user').value,gel('pass').value)">Log In (callback)</button>&nbsp;<button onclick="logInAwait(gel('user').value,gel('pass').value)">Log In (async)</button>
</pre>
<hr/>
<pre id='result'></pre>

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

Is there a way to transfer a variable from Angular 2 Frontend Express JS to an Angular 2 component?

After conducting thorough research, I have made specific modifications to my code. However, I am encountering some errors in my console that I cannot seem to resolve. Despite following a tutorial step by step. Your assistance would be highly valued as I a ...

Obtaining a variable from within two nested functions

I'm looking for a solution where I can retrieve a variable from inside a function using an ajax call. For example: function returnStuff(){ $.ajax({ //do something }).done(function(response){ return response; }) return response; } The ...

The useEffect function is not being executed

Seeking assistance from anyone willing to help. Thank you in advance. While working on a project, I encountered an issue. My useEffect function is not being called as expected. Despite trying different dependencies, I have been unable to resolve the issue ...

JavaScript Memory Game: Enhance User Experience with Hover Effects on Tiles

Looking for some assistance with JavaScript code I've written for a memory game on Khan Academy. I'm struggling to figure out how to change the color of a tile when the mouse hovers over it. I attempted to draw a star on a tile within the "if (ti ...

Fade out embedded images or target specific classes when hovering over them with the mouse

Is it feasible to use JavaScript or jQuery to fade only the embedded image instead of the entire div, revealing the background image of the div? I have multiple instances of the classes below and wish to apply these changes only to the selected ones. For ...

Unable to retrieve values from JSON objects within an array

My array consists of multiple objects, each containing specific properties such as: [ { "id":17368, "creationDate":1566802693000, "status":"InProgress", "type":"NEW", "agentType":"Master" }, { "id":17368, ...

Activate a button only when a value is inputted into a text box associated with a chosen radio button

I'm facing a challenge with my radio buttons and sub-options. When a user selects an option, the corresponding sub-options should be displayed. Additionally, I want to enable the next button only when text is entered in all sub-option text boxes for t ...

Displaying text within an HTML table featuring a vibrant background

I'm having trouble printing a basic certificate that is formatted as an HTML table. There are a couple of frustrating issues I'm facing. 1) When I try to print the table using Chrome, my CSS changes are not being applied. 2) I can't seem to ...

Displaying PDF content in a new browser tab by utilizing JavaScript

Currently, I am utilizing the struts2 framework alongside dojo for the UI. My goal is to display a PDF in a new browser window. The PDF inputstream is obtained from the server through a standard AJAX call using the GET method (not utilizing a Dojo AJAX cal ...

What is the best way to order an array of objects within a MongoDB collection?

Currently, I am working with node.js and MongoDB. In my collection, I have defined the following schema: var project = new Schema({ head:{ head_task: String, userID: String }, access_users: { type : Array , "default" : []}, context_task: [ ...

What is the best way to create a scrollable Material UI modal and dialog?

Having a problem with my mui modal where the top content is getting cut off and I can't scroll up. I've tried adding the {overflow:"scroll"} property to the modal but it's not working. Here's the code snippet I'm currentl ...

Create a page turning effect in React that simulates scrolling a certain amount at a time

Is there a way to disable default scrolling and have the page automatically scroll to the next item? For example, if I have element2 below element1, how can I set it up so that when I scroll down once, the page scrolls directly to the position of element2 ...

What is the procedure for importing material UI components into the main class?

Hey there! I'm currently working on integrating a "SimpleAppBar" element into my React app design. Below is the code snippet for this element sourced directly from the Material UI official website: import React from 'react'; import PropType ...

Struggling with developing a straightforward application with Angular-Material

My goal is to develop an application that utilizes the Angular Material navigation bar, as showcased in this example. Being relatively new to AngularJS, I'm facing an issue where my app loads but only displays a blank page. Below is the code snippet ...

Is there a minimum length validator available for Mongoose as an option

Is there a way to create an optional string field type with a specified minimum length? I've read through the documentation but couldn't find clear instructions on how to achieve this. Here's what I've attempted: var schema = mongoose. ...

Displaying the React input text currently

I am currently working on creating a custom composed input text by combining 4 input components together, but I seem to be encountering some difficulties. Even though everything appears to be set up correctly, the only way I have managed to display the in ...

Retrieving text data in Controller by utilizing jQuery AJAX request

Text box and button for input <input type="text" class="form-control" name="ClaimNumber" placeholder="Enter a claim number" id="ClaimNumber" /> <button class="btn btnNormal" type="submit" id="btnSearch"> ...

Tumblr jQuery Like (utilizing rel attribute for selection)

I developed a custom HTML5 theme using masonry and infinite-scroll, which has been functioning well. I am now trying to add reblog and like buttons to each post but I'm facing an issue with the like button not working. Here is the URL to the theme: ...

It is impossible to conceal the internal element if its height or width is set to 0px

Is there a way to toggle a div's width or height? I tried setting the width to 0, but the inner element remained visible. Any suggestions on how to achieve this toggle width functionality? Check out the solution on JS Fiddle a { display: block ...

Adjust the appearance of a .obj file in three.js dynamically

Currently, I am attempting to dynamically swap the image texture on a loaded .obj file in three.js. Below is the modified code extracted from the three.js examples: var container, stats; var camera, scene, renderer; var mouseX = 0 ...