0

I am creating a typeahead search to find tags from a mongodb collection. Im not sure how to return the results (for every keystroke) so that it will dropdown with options and then populate the solution for the tag.

I have followed the wikipedia example found here: https://ng-bootstrap.github.io/#/components/typeahead/examples

I have a service which I pass a search term into and then I run a find in the searchDB.js in order to return back the results.

When I return the reponse all I get is a whole lot of code in my terminal - starting with ServerResponse {....

I just cant get it to return the results.

// This is my search.js

const mongoose = require('mongoose');
const bcrypt = require('bcrypt');

const { Schema } = mongoose;

// create a schema
const searchSchema = new Schema({
  tag: String,
  solutions: Array
});

const Search = mongoose.model('Search', searchSchema);

module.exports = Search;

// This is in my searchDB.js

const express = require('express');
const Search = require('../models/search');

const router = express.Router();

/* GET api listing. */
router.get('/:text', (req, res) => {

  var q = req.params.text;

  Search.find({
    $text: {
      $search: q
    }
  }, {
    _id: 0,
    __v: 0
  }, function (err, data) {
    res.json(data)
  });

});

module.exports = router;
// This is in my search.service.ts

search(term: string) {
    if (term === '') {
      return of([]);
    }

    return this.http.get(`/db/search/${term}`).pipe(
        map(response => response[1])
    );
  }
// This is in my search.compponent.ts

search = (text$: Observable<string>) =>
      text$.pipe(
        debounceTime(300),
        distinctUntilChanged(),
        tap(() => this.searching = true),
        switchMap(term =>
          this._service.search(term).pipe(
            tap((searchResults) => { console.log(searchResults); this.searchFailed = false; }),
            catchError(() => {
              this.searchFailed = true;
              return of([]);
            }))
        ),
        tap((searchResults) => { console.log(searchResults); this.searching = false; })
      )
// This is my search.component.html

<input id="search" name="search" [ngbTypeahead]="search" type="text" placeholder="Search for solutions..." class="form-control-search-bar form-control-underlined amcs-search">

// This is what my mongo db collection looks like

{ 
    "tag" : "truck", 
    "solutions" : [
        {
            "id" : 1, 
            "title" : "where is the truck"
        }, 
        {
            "id" : 1234, 
            "title" : "What is a rubbish truck"
        }, 
        {
            "id" : 12345, 
            "title" : "Do vans or lorrys or trucks take bins"
        }
    ]
}
{ 
    "tag" : "bin", 
    "solutions" : [
        {
            "id" : 1230, 
            "title" : "Do vans or lorrys or trucks take bins"
        }
    ]
}

When a user types "tr" into the search bar I want the dropdown display all the solution titles that have the tag starting with "tr" - in this case truck. Or if it was "b" then the tag bin would show its solution titles in the dropdown. The solution ID will be used as a link so that when the title is clicked it will be directed to that id.

Andrew
  • 227
  • 1
  • 5
  • 16
  • 2
    `$text` is not the right thing for the sort of results you are after. You are describing what is actually a `$regex` search. Also, it was probably something you just did in testing at some stage, but the code `map(response => response[1])` is almost certainly wrong since I would be reasonably sure you did not intend to only ever read the second result from an an array of results and discard all others. Not related to the current problem of course, but just a "heads up" in case you missed/forgot about that. – Neil Lunn Nov 04 '19 at 11:40
  • Thank you @NeilLunn - I followed the steps you have sent through and I can see the array in the console log but I also get an error saying that Cannot find a differ supporting object '[object Object]' of type 'object'. NgFor only supports binding to Iterables such as Arrays. I changed the code in the searchDB to be: `Search.find({"tag":{'$regex': req.params.text}}, function (err, data) { res.json(data) }); ` Any ideas on why? I googled this and it seemed to be something to do with json being returned but when I added in the json solution it broke it all. – Andrew Nov 04 '19 at 13:11
  • 1
    Well "I also get the error.." ( AKA, yes I learned something from the referenced answers but now have a new problem ) essentially means you have a **new problem** and therefore a new question. You could ask a new question, or you could have just searched for that and found [How can I display a JavaScript object?](https://stackoverflow.com/a/4293047/2313887). Please post new questions when you have a new question. The one question you asked is not meant to be a never ed\ending comment chain of discussion. – Neil Lunn Nov 05 '19 at 09:21

0 Answers0