[英]how to get a particular user data from MongoDB in node.js
I'm doing a project on an e-commerce website.我正在电子商务网站上做一个项目。 here I'm with a problem.
我遇到了一个问题。
Im trying this but the solution im getting is all the users data我正在尝试这个,但我得到的解决方案是所有用户数据
i have tried using findOne() but the result is this 635ea7e5e931e12c9f851dd3 user details.我试过使用 findOne() 但结果是这个 635ea7e5e931e12c9f851dd3 用户详细信息。 where the parameter is 63a8a0f77addf42592eed1e5.
其中参数为 63a8a0f77addf42592eed1e5。 where im expecting to get the only user which im passing in parameter.
我希望获得唯一传入参数的用户。
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
The req.params userId is '63a8a0f77addf42592eed1e5'. req.params userId 是“63a8a0f77addf42592eed1e5”。 i need only this.
我只需要这个。 but it is popping up all the users data.
但它正在弹出所有用户数据。
Node.js terminal showing the parameter is same with userId Node.js终端显示参数与userId相同
Postman showing the response of all users present in the DB but i need only the user details which i had passed in the parameter Postman 显示了数据库中所有用户的响应,但我只需要我在参数中传递的用户详细信息
Here the mongoDB find
method returns all data in the collection, irrespective of the parameters that we pass in to it.这里的 mongoDB
find
方法返回集合中的所有数据,无论我们传递给它的参数如何。 Instead try using the findOne
method for that collection.而是尝试对该集合使用
findOne
方法。 So the code with correction will be as follows:所以修正后的代码如下:
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.findOne(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
return res.status(200).json(cart);
} catch (err) {
res.status(500).json(err);
}
You can read more about the method at MongoDB Manual .您可以在MongoDB 手册中阅读有关该方法的更多信息。
I had found the solution for my problem ie I have used filter method at ( res(200).json(cart.filter(((user)=>user.UserId === req.params.userId)
)我找到了解决我的问题的方法,即我在 (
res(200).json(cart.filter(((user)=>user.UserId === req.params.userId)
)
This means这意味着
UserId
in my model === to the parameters userId
UserId
到参数userId
router.get("/find/:userId", verifyTokenAndAuthorization, async (req, res) => {
try {
const cart = await Cart.find(
{userId : req.params.userId});
console.log("parameter: "+req.params.userId)
res.status(200).json(cart.filter((user)=>user.UserId === req.params.userId));
console.log(cart.filter((user)=>user.UserId === req.params.userId))
} catch (err) {
res.status(500).json(err);
}
});
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.