javascript - 尝试从客户端输入动态设置 .find() 参数 - mongodb:Atlas
问题描述
我正在尝试使用来自客户端的数据,他们会在输入框中输入这些数据。这个想法是使用它在我的数据库中查找以使用相同的用户名提取数据。在我的 Mongo DB:Atlas 收藏中。
所以它像这样使用它从数据库中获取名称,.find({"username": request.body})
但是,我不断收到错误“CastError: Cast to string failed for value "{ username: '' }" (type Object) at path "username" for model "Db1"在我的终端上。
但是当我尝试将它硬编码到 .find({"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);
}
});
});
推荐阅读
- c# - 从 .Net 调用 AWS Step Functions
- ajax - Wordpress:从帖子ID(ajax)返回页面的HTML
- php - json_decode() 期望参数 1 是给定的字符串数组
- javascript - 用树状结构组织数据列表中的节点
- javascript - 使用 iframe 检测不活动
- python - 以 Excel 形式读取 Pandas - Python
- c# - 如何将字典中的所有值从一个键加到下一个键?
- node.js - 如何调试挂着的快递服务器?
- mocha.js - 坚固 | 摩卡 | 地址不是合同
- php - 存储注册状态未正常工作(始终存储值“C”但如果注册已付费则应存储“I”)