The array stored in my MongoDB looks like this:
[
{
"_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
}
]
As you see, 2 objects have same age as 2 and 1 have age as 3. I want to query from node.js by age, so that when I query by age 2, I get an array with objects having age 2. Currently findById works for me with query as id.
Here is the code:
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
});
});
};
How do I query by age?