Problem to query MongoDB through collection.find from simple text box in browser page

Hi,
I use a mongodb database where I have its internal log data. With Express, Node and Monk (following this guide) I have to try to get data from a search text box, and I stopped on how to request this data.

from the userlist.ejs page I have implemented a form where I send a GET request:

`http://localhost:3000/userlist?name=5044`

where then I go to get name through

search = req.query.name 

and then insert it into the collection.find({search}…

below is the index.js:

/* GET Userlist page. */
router.get('/userlist', function(req, res) {

    search = req.query.name;

    var db = req.db;
    var collection = db.get('startup_log');
    collection.find({search},{},function(e,docs){
        res.render('userlist', {
          "userlist" : docs
    });
});

});

this is the userlist.ejs page where I send the request. which later should display it through the for loop after processing it from index.ejs,

 <!DOCTYPE html>
<html>
   <head>
     <title>User List</title>
     <link rel='stylesheet' href='/stylesheets/style.css' />
   </head>
 <body>
     <h1>User List</h1>

     <input type="text" id="titles" />

<form action="/userlist" method="GET" encType="multipart/form-data">
  <label htmlFor="newNote">New Note:</label>
    <input type="text" name="name"  className="form-control" rows="5" 
     id="name" placeholder="5044"></input>
    <button id="done" type="submit" className="btn btn-primary pull- 
     right">Done</button>
    <button id="cancel" className="btn btn-warning pull- 
   right">Cancel</button>
</form>

 <ul>
    <% for (var i = 0; i < userlist.length; i++) {%>
 
    <li><%= userlist[i].hostname %></li>
     
        <li></li>        
     <%}%>
  </ul>
 </body>
</html>

i can’t figure out how to pass to collection.find the query i enter in the text box! any help would be appreciated as I cannot find specific information about my case. Thanks in advance!

Okay so a few questions to help narrow down where your bug is at.

  1. If you call
collection.find({},{},function(e,docs){
        res.render('userlist', {
          "userlist" : docs
    });

Do you get a response?
2. Have you tried to console.log your req.query.name to make sure you are getting what you think you are?

Thanks for the reply! I get what I need in console.log, I think the ejs page is loaded together with the GET of the index.js before I execute the onclick request

The problem is not the ejs file. Because you send it when you have received the answer from the db.

It seems that you use mongodb.js so try this:

router.get('/userlist', (req, res) => {

    search = req.query.name;
    var db = req.db;
    var collection = db.get('startup_log');
    collection.find({search}).toArray((err, docs)=>{
               if(err) {
                          return res.render('userlist', {userlist: []})
               }
        res.render('userlist', {
              userlist : docs
          });
    });

Maybe I’m misunderstanding what you are trying to do, I also just briefly looked at the article.

The userlist route is just a GET to list out all the users in the DB. They do not use that route for the form in part 4, they use newuser which is a POST, not a GET.

Also, just as an aside, the enctype for simple text form submit is usualy application/x-www-form-urlencoded and multipart/form-data is usually used for files.

yes basically I’m trying according to the article to implement a function with a search field in the ejs page, but without getting any results!

regarding the solution presented by wumpelchen i get this error:

collection.find(…).toArray is not a function.

basically I would just like to receive the parameters I search for in the text box, NOT all the records …
thanks everyone for the help

at this point it occurs to me that the error is in:

`http://localhost:3000/userlist?name=5044`

and

router.get('/userlist', function(req, res) {

i should do GET on:

router.get('/userlist/userlist?name=', function(req, res) {

or something similar that I cannot momentarily do.
my impression, in your opinion, am I wrong?

guys amazing but true, i’m still stuck, i didn’t really expect it :slight_smile:

in my hated index.js```

var express = require('express');

var router = express.Router();

var express    = require('express');

var bodyParser = require('body-parser');

//----

//-----

var app = express();

app.use(bodyParser.urlencoded({

    extended: true

  }));

//...................

function simplify(text) {

  const separators = /[\s,\.;:\(\)\-'\+]/g;

  const diacritics = /[\u0300-\u036f]/g;

  //capitalização e normalização

  text = text.toUpperCase().normalize("NFD").replace(diacritics, "");

  //separando e removendo repetidos

  const arr = text

    .split(separators)

    .filter((item, pos, self) => self.indexOf(item) == pos);

  console.log(arr);

  //removendo nulls, undefineds e strings vazias

  return arr.filter((item) => item);

}

//.................................

//___________________________________________________////

router.get("/search", function (req, res, next) {

  if (!req.query.name)

    return res.render("search", {

      title: "NodeMongo Search",

      userlist: [],

      query: "",

    });

  else {

  const query = simplify(req.query.name);

  const mongoClient = require("mongodb").MongoClient;

  mongoClient

    .connect("mongodb://localhost:27017")

    .then((conn) => conn.db("local"))

    .then((db) => db.collection("startup_log").find({ tags: { $all: query } }))

    .then((cursor) => cursor.toArray())

    .then((userlist) => {

      return res.render("search", {

        title: "NodeMongo Search",

        userlist,

        query: req.query.name,

      });

    });

    console.log(query);

}

});

module.exports = router;

in my dear search.ejs (I changed some names)


<!DOCTYPE html>
<html>
  <head>
    <!-- Required meta tags -->
    <meta charset="utf-8" />
    <meta
      name="viewport"
      content="width=device-width, initial-scale=1, shrink-to-fit=no"
    />
    <title><%= title %></title>
    <!-- Bootstrap CSS -->
    <link
      rel="stylesheet"
      href="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/css/bootstrap.min.css"
      integrity="sha384-9aIt2nRpC12Uk9gS9baDl411NQApFmC26EwAOH8WgZl5MYYxFfc+NcPb1dKGj7Sk"
      crossorigin="anonymous"
    />
  </head>
  <body>
    <div class="container">
      <div class="row h-100">
        <div class="col-sm-12 align-self-center">
          <h2 class="text-center mb-5"><%= title %></h2>

          <form action="" method="GET">
            <div role="group" class="input-group">
              <input
                class="form-control"
                type="text"
                placeholder="Search here"
                class="form-control"
                name="name"
                value="<%= query %>"
              />
              <div class="input-group-append">
                <input
                  type="submit"
                  name=""
                  id=""
                  class="btn btn-primary input-group-append"
                  value="Pesquisar"
                />
              </div>
            </div>
          </form>

          <hr />

          <ul class="list-group">
            <% for(let i=0; i < userlist.length; i++) { %>
            <li class="list-group-item">
              <strong><%= userlist[i].pid %></strong> (<%= userlist[i].startTime %>)
              <div class="text-muted">
                Starring <%= userlist[i].hostname %> 
              </div>
            </li>
            <% } %>
          </ul>
        </div>
      </div>
    </div>

    <style>
      html,
      body {
        height: 100% !important;
      }

      /* CSS only for examples not required for centering */
      .container {
        height: 100% !important;
        max-width: 600px;
      }

      /* show border around full height container */
    </style>

    <script
      src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
      integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://cdn.jsdelivr.net/npm/popper.js@1.16.0/dist/umd/popper.min.js"
      integrity="sha384-Q6E9RHvbIyZFJoft+2mJbHaEWldlvI9IOYy5n3zV9zzTtmI3UksdQRVvoxMfooAo"
      crossorigin="anonymous"
    ></script>
    <script
      src="https://stackpath.bootstrapcdn.com/bootstrap/4.5.0/js/bootstrap.min.js"
      integrity="sha384-OgVRvuATP1z7JjHLkuOU7Xw704+h835Lr+6QL9UvYjZE3Ipu6Tp75j7Bh/kR0JKI"
      crossorigin="anonymous"
    ></script>
  </body>
</html>

I don’t know where to turn my head anymore, in the console log (query) is read without any problem, as long as I put a field in mongo instead of query I find it without any problem, unfortunately it does not pass the value I am looking for from the search box … incredible but true! if some kind user can help me I would be very able, it has become a personal matter :slight_smile:

it will be tiredness, it will be what it will be but I’m going crazy!

PS I have tried them all!