gpt4 book ai didi

javascript - 通过属性获取MongoDB中存储的数组

转载 作者:行者123 更新时间:2023-12-02 21:36:40 24 4
gpt4 key购买 nike

存储在我的 MongoDB 中的数组如下所示:

[
{
"_id": "1",
"name": "X",
"age": "2",
"createdAt": "2020-02-29T22:22:49.491Z",
"updatedAt": "2020-02-29T22:22:49.491Z",
"__v": 0
},
{
"_id": "2",
"name": "A",
"age": "3",
"createdAt": "2020-02-28T22:22:49.491Z",
"updatedAt": "2020-02-28T22:22:49.491Z",
"__v": 0
},
{
"_id": "3",
"name": "B",
"age": "2",
"createdAt": "2020-02-29T12:22:49.491Z",
"updatedAt": "2020-02-29T12:22:49.491Z",
"__v": 0
}
]

如您所见,2 个对象的 age 与 2 相同,而 1 个对象的 age 为 3。我想通过 age 从 node.js 查询code>,这样当我按 age 2 查询时,我会得到一个包含 age 2 的对象的数组。目前 findById 适用于我的查询作为id

这是代码:

exports.findByAge = (req, res) => {
Property.findById(req.params.propertyId)
.then(property => {
if (!property) {
return res.status(404).send({
message: "Not found " + req.params.propertyId
});
}
res.send(property);
}).catch(err => {
if (err.kind === 'ObjectId') {
return res.status(404).send({
message: "Not found with id " + req.params.propertyId
});
}
return res.status(500).send({
message: "Error retrieving property with id " + req.params.propertyId
});
});
};

如何按年龄查询?

最佳答案

您应该引用Find Documents with a Query Filter in Mongodb并将其用于过滤带有 age 字段的文档。并阅读此链接 Comparison Query Operators .

exports.findByAge = (req, res) => {
Property.find({ age: { $eq: req.params.age } })
.then(property => {
if (!property) {
return res.status(404).send({
message: "Not found " + req.params.propertyId
});
}
res.send(property);
}).catch(err => {
if (err.kind === 'ObjectId') {
return res.status(404).send({
message: "Not found with id " + req.params.propertyId
});
}
return res.status(500).send({
message: "Error retrieving property with id " + req.params.propertyId
});
});
};

您可以使用cursor.sort()对即将到来的数据进行排序将其添加到find之后。

Property.find({ age: { $eq: req.params.age } }).sort({ _id: -1 })

在排序参数中指定要排序的一个或多个字段,并指定值 1 或 -1 分别指定升序或降序排序。

关于javascript - 通过属性获取MongoDB中存储的数组,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60474273/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com