Question: NodeJS returns no results with Elasticsearch / Mongoosastic

Question

NodeJS returns no results with Elasticsearch / Mongoosastic

Answers 1
Added at 2016-12-23 08:12
Tags
Question

I'm trying to create a simple search form to search in one Model (Products).

Here is my Product Model using Mongoosastic:

var ProductSchema = new Schema({
    category: { type: Schema.Types.ObjectId, ref: 'Category'},
    name: String,
    price: Number,
    image: String,
    description: String
});

ProductSchema.plugin(mongoosastic, {
    hosts: [
         'localhost:9200'
    ]
});

I connect ElasticSearch with Product model like so:

Product.createMapping(function (err, mapping) {
    if (err) {
      console.log("error creating mapping");
      console.log(err);
    } else {
      console.log("Mapping created");
      console.log(mapping);
    }
});

var stream = Product.synchronize();
var count = 0;
stream.on('data', function () {
  count++;
});
stream.on('close', function () {
   console.log("Indexed" + count + " documents");
});
stream.on('error', function (err) {
    console.log(err);
});

After that I created the GET method to render the results page like so:

router.get('/search', function (req, res, next) {
if (req.query.q){
    Product.search({
        query_string: { query: req.query.q }
    }, function (err, results) {
        if (err) return next(err);
        var data = results.hits.hits.map(function (hit) {
            return hit;
        });

        res.render('main/search-result', {
            query: req.query.q,
            data: data
        });
        console.log(data);
    });
}
});

And in the frontend page I loop through results like so:

    <div class="row">
    <% for (var i = 0;i < data.length; i++){%>
    <div class="col-md-4">
        <a href="/product/<%= data[i]._source._id %>"></a>
        <div class="thumbnail">
            <img src="<%= data[i]._source.image%>" alt="">
            <div class="caption">
                <h3><%= data[i]._source.name %></h3>
                <h4><%= data[i]._source.category.name %></h4>
                <h5><%= data[i]._source.price %></h5>
                <p><%= data[i]._source.description %></p>
            </div>
        </div>
    </div>

    <% } %>
</div>

In the terminal everything is Ok

Server is Running on port 3000
Mapping created
{ acknowledged: true }
Connected to the database
Indexed120 documents

Why are there no results rendered on my page?

Answers
nr: #1 dodano: 2016-12-25 12:12
  1. Check your Database. Is there any record in the document?
  2. Print the query parameter. And also print the search query.
  3. Check your URL with Postman.
Source Show
◀ Wstecz