【发布时间】:2020-03-01 19:54:57
【问题描述】:
存储在我的 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 中查询,所以当我通过 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
});
});
};
如何通过age查询?
【问题讨论】:
标签: javascript arrays node.js mongodb express