javascriptnode.jsexpressnedb

NEDB & Nodejs: searching for specific record in home.db using user input - unable to pass parameter to index.js


STUDENT WARNING. I am learning to use Nodejs, express with NEDB and database. I am attempting to query my home.db (NeDB) for a specific record, making use of user input (in this case, the name of a person). High-level diagram of the process: High-level record request process

Process (in my mind) flows as follows:

  1. User input captured in home.html input & GET is clicked
  2. searchSpecific() in home.js is called where fetch() executes
  3. index.js (server) receives request and app.get() is called
  4. app.get() returns result to home.js
  5. home.js dynamically updates table with result (lets assume the record exists in the db)
  6. ends

Results being aimed for:

  1. success or failed attempt notification to user on home.html
  2. partial matching of user input vs db records to be attempted & returned

Here is what I cant get to work:

  1. The ability to pass the user input from home.html into home.js fetch() to enable the server index.js db.home.find( { : /value/}...) to search for the record

When reviewing the NeDB docs, the code seems to only apply to index.js and does not advise on home to call the api from another webpage and providing proper data structure. I feel that I still have much to learn about HTTP requests and thus am struggling, but beginner-friendly info for NeDB is not easy to find (dare I say in short supply).

Current code samples: home.html

<div class="container">
  <label for="Name">Search by name</label>
  <input type="text" class="searchInput" value="" />
  <button class="searchBtn">Get</button>
  <button class="clearBtn">Clear</button>
</div>

home.js

async function searchSpecific() {
 let getName = searchInput.value;

 const response = await fetch("/api-specific", getName);
 const data = await response.json();
}

index.js

app.get("/api-specific", (request, response) => {
  const searchCriteria = request.name;
  home.find({ getName: searchCriteria }, (err, data) => {
    if (err) {
      console.log(err);
      response.end();
      return;
    }
    response.json(data);
  });
});

home.db sample

{"getName":"Beau Latting","getEmail":"latting@gmail.com","getStartDate":"2021-02-01","getTime":1623757169311,"_id":"kNcNjbQo1OPO34lb"}
{"getName":"Martin Ras","getEmail":"martinjnr@gmail.com","getStartDate":"2021-01-10","getTime":1623757374409,"_id":"nu5L5Sc0DN9PximD"}
{"getName":"William Blue","getEmail":"will@blue.com","getStartDate":"2021-06-18","getTime":1623747050246,"_id":"wUqP818jNX6Fw6tb"}

Closing comment. Thank you for giving your time to try and help me with this. I have considered trying for assistance on stackO very carefully, as I know I will be hammered if I seem research-lazy, but I can assure you that after a week of trying, I need help. I am convinced that I do not currently know how to search for what I am trying to achieve. Please be gentle.

Thanks in advance


Solution

  • I managed to get it to work by using POST instead of GET. Not much info out there for my specific case and I still dont understand why, but its working now.

    Eventlistener:

    searchBtn.addEventListener("click", () => {
      let userSearch = {
        name: searchInput.value,
      };
    
      searchSpecific("/api-homeSpecific", userSearch).then((data) => {
        updateDom(data);
      });
    });
    

    Async function to node server:

    async function searchSpecific(url = "", data = {}) {
      const response = await fetch(url, {
        method: "POST",
        mode: "cors",
        cache: "no-cache",
        credentials: "same-origin",
        headers: {
          "Content-Type": "application/json",
        },
        referrerPolicy: "no-referrer",
        body: JSON.stringify(data),
      });
      return response.json();
    }
    

    Node service to DB: //SPECIFIC Search test

    app.post("/api-homeSpecific", (request, response) => {
      let inputReceived = request.body.name;
      //console.log("input Received: ", inputReceived);
    
      home.find(
        { getName: { $regex: new RegExp(inputReceived.toLowerCase(), "i") } },
        (err, data) => {
          if (err) {
            console.log(err);
            response.end();
            return;
          }
          console.log("Request for SPECIFIC USER data executed");
          // console.log(data);
          response.json(data);
        }
      );
    });
    

    RESULT: user entered some search criteria and that specific criteria gets passed into the home.find() parameter and returns anything matching (full or partial match). The use case for this when a user wants to find out whether "Bill Brown" is a member using the only info available = the name.