首页 > 解决方案 > 尝试从客户端输入动态设置 .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);

标签: javascriptnode.jsmongodbserver

解决方案


实际上,您正在将对象传递{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);
    }
  });

});

推荐阅读