gpt4 book ai didi

node.js - NodeJS 使用 Elasticsearch/Mongoosastic 不返回任何结果

转载 作者:太空宇宙 更新时间:2023-11-03 22:28:43 24 4
gpt4 key购买 nike

我正在尝试创建一个简单的搜索表单来在一个模型(产品)中进行搜索。

这是我使用 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'
]
});

我将 ElasticSearch 与产品模型连接起来,如下所示:

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);
});

之后,我创建了 GET 方法来呈现结果页面,如下所示:

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);
});
}
});

在前端页面中,我循环遍历结果,如下所示:

    <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>

在终端中一切正常

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

为什么我的页面上没有呈现任何结果?

最佳答案

  1. 检查您的数据库。文件中有记录吗?
  2. 打印查询参数。并打印搜索查询。
  3. 使用 Postman 检查您的URL

关于node.js - NodeJS 使用 Elasticsearch/Mongoosastic 不返回任何结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41296963/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com