gpt4 book ai didi

javascript - 根据用户输入从 api(RESTful) db(mongodb) 获取数据

转载 作者:太空宇宙 更新时间:2023-11-04 01:45:59 25 4
gpt4 key购买 nike

我使用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);
}
});
});

最佳答案

在进行 api 调用时,将 dish 作为查询参数传递

例如'/recipes/?dish="Pizza"'

并明确使用以下内容。

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

关于javascript - 根据用户输入从 api(RESTful) db(mongodb) 获取数据,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/51463875/

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