尝试从客户端输入动态设置.find()参数-mongodb:Atlas



我正在尝试使用客户端的数据,他们会将这些数据输入到输入框中。我们的想法是使用它在我的数据库中查找具有相同用户名的数据。在我的Mongo DB:Atlas收藏中。

因此,它可以像这样使用它来从数据库中获取名称,.find({quot;username":request.body}(

然而,我不断地得到错误"CastError:值"的强制转换为字符串失败;{用户名:"}"(类型Object(在路径"处;用户名";对于模型";Db1">在我的终端上。

但当我尝试将其硬编码到.find({quot;username":"name"上时,它运行良好。有人有什么想法吗?

**Javascript app**
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);
};
```
-----------------------------------------------------
**Node Server**
app.post('/database', (request,response) => {
const info = request.body;
postModel.find({"username": info}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});
----------------------------------------------
***client side DB***
async function pullData () {
let clientQ = document.querySelector('#userDB').value;
let entry = {
'username':clientQ
};
const options = {
method: "POST",
headers: {
'Content-Type': 'application/json',
},
body: JSON.stringify(entry)
};
const getData = await fetch('/database', options);
const request = await getData.json();
console.log(request);

实际上,您正在将对象{username : "value"}传递给find方法。你需要传递字符串。

app.post('/database', (request,response) => {

const info = request.body; // object {username : "value"}
const username = info.username; // the string to search by username
postModel.find({"username": username}, (error,data) => {
if(error){
console.log(error);
} else {
response.json(data);
}
});
});

最新更新