我希望我的网站在顶部的搜索栏中返回mongo数据库中的单个文档(墨水)。在同一页面上,我希望能够从同一数据库访问所有文档。
我很难在一个页面上弄清楚如何执行此操作,因为我只能将一个结果发送到URL。
是否有某种方法可以将所有文档发送到页面,然后在客户端与Ajax进行搜索?我是新手编码的,想知道我是否犯了这个错误。
我感谢任何帮助。这是我的代码的一部分,它发送了我想要的结果,但要发送给不同的页面。
app.get("/", function(req, res){
// FIND ONE INK FROM DB
var noMatch = null;
if(req.query.search) {
Ink.find({ink: req.query.search}, function(err, foundInk){
if(err){
console.log(err);
} else {
if(foundInk.length < 1) {
noMatch = "No match, please try again.";
}
res.render('new-index', {ink: foundInk, locationArray: locationArray, noMatch: noMatch })
}
});
} else {
// FIND ALL INKS FROM DB
Ink.find({}, function(err, allInks){
if(err){
console.log(err);
} else {
res.render("index", {ink: allInks, locationArray: locationArray, noMatch: noMatch });
}
});
}
});
您可以为每个请求使用分开的端点。对于完整的访问请求,您可以渲染页面,调用res.render
,以及搜索请求,可以返回JSON调用res.json
。这样的东西:
app.get("/", function(req, res){
// FIND ALL INKS FROM DB
Ink.find({}, function(err, allInks){
if(err){
console.log(err);
} else {
res.render("index", {ink: allInks, locationArray: locationArray, noMatch: noMatch })
}
});
})
app.get("/search", function(req, res) {
// FIND ONE INK FROM DB
var noMatch = null;
Ink.findOne({ink: req.query.search}, function(err, foundInk){
if(err){
console.log(err);
} else
if(!foundInk) {
noMatch = "No match, please try again.";
}
res.json({ink: foundInk, locationArray: locationArray, noMatch: noMatch })
}
});
});
请注意/search
处理程序中Ink.findOne
的呼叫,该电话仅返回一个文档。
这样,您可以做出和ajax请求/搜索,然后解析JSON从服务器返回的JSON。
我在此创建了一个带有完全相同问题的示例存储库
理想情况下,您可以做一个这样的终点。
( id parameter is optional here...thats why the '?' )
www.example.com/api/inks/:id?
// return all the inks
www.example.com/api/inks
// return a specific ink with id=2
www.example.com/api/inks/2
所以现在您可以通过/inks
呈现所有链接,并使用端点/ink/:id?
希望这会有所帮助!