如何显示 json get 请求,其中 _something_ 等于 _othersomething_ (Node.js



我在req.params.id里面有一个id

var id = req.params.id // let's say this is 2

假设我有来自MongoDB的:

[
{
"text": "hello",
"fromId": "1"
},
{
"text": "hi",
"fromId": "1"
},
{
"text": "hey",
"fromId": "2"
},
]

我用它来查询:

const message = await Message.find().select('text fromId');
const fromId = await Message.distinct('fromId');

我想要这样的东西(但当然这段代码是不恰当的(:

res.json(message).where(id === fromId);

所以我只想得到这个,因为我的 id 是 2,fromId 是 2:

{
"text": "hey",
"fromId": "2"
},

我希望 get 请求res.json()仅显示id 等于 fromId的那些。

将过滤器对象传递给find函数,以仅获取fromId等于req.params.id

的文档
const message = await Message.find({ fromId: req.params.id })

我相信你只是在寻找

const message = await Message.findOne({"fromId": "2"})

您还应该添加.lean()以便它返回简单的 JSON 并且速度更快,并且.exec()非阻塞。

完整代码 :

const message = await Message.findOne({fromId: req.params.id}).lean().exec();
res.json(message);

你为什么不使用猫鼬?如果不使用ORM是个人偏好,我理解,但如果您确实改变了主意。就像

const message = await Message.findById(id);  // This only takes mongoDB ids as arguments
// Use this for another general field
const message = await Message.findOne({fromId : id})
res.json(message).status(200);

您还可以将其包装在 try catch 块中,以便在找不到带有 id 的文档时处理任何错误。

最新更新