提问人:Bhagya Swamy 提问时间:7/22/2018 最后编辑:Bhagya Swamy 更新时间:7/23/2018 访问量:595
根据用户输入从 api(RESTful) db(mongodb) 获取数据
Fetch data from api(RESTful) db(mongodb) according to user input
问:
我使用 nodejs、express 和 mongodb 创建了一个 api。我现在正在获取数据而不发送任何查询。但是在我的前端,我有一个输入,用户可以在其中搜索食谱。因此,例如,如果用户键入“今天”,我应该只得到与今天相关的响应。如何在数据库中检查并检索数据?
module.exports = function(app, db) {
app.get("/dates/", (req, res) => {
db
.collection("dates")
.find()
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});
答:
0赞
Anshul Bansal
7/22/2018
#1
在进行 api 调用时,传递 as 查询参数dish
例如,'/recipes/?dish=“Pizza” '
并在 express 中使用以下内容。
module.exports = function(app, db) {
app.get("/recipes/", (req, res) => {
let queryDish = req.query.dish; // assuming /recipes/?dish="Pizza"
let query = { 'title' : { '$regex' : queryDish, '$options' : 'i' } };
db
.collection("recipes")
.find(query)
.toArray((err, item) => {
if (err) {
res.send({ error: "An error has occured" });
} else {
res.send(item);
}
});
});
评论
0赞
Bhagya Swamy
7/22/2018
Anshul,我的数据对象如下。我必须检查我的对象的标题是否存在该查询。{ "_id": "5b5446df2c89ab3d0e8d5526", "title": "Chicken with Mustard Cream Sauce", "vegetarian": false, "ingredients": [ "4 whole Boneless Skinless Chicken Breasts", ], "image_url": "http://static.food2fork.com/chickenmustarde587.jpg", "steps": [ "Amount of cream and broth has slightly ], "serving": 5, "cooking_time": 20 },
0赞
Anshul Bansal
7/22/2018
在这种情况下,您可以修改查询,使匹配不区分大小写。更新了答案以反映该@BhagyaSwamy
评论
find()