Warning: file_get_contents(/data/phpspider/zhask/data//catemap/3/arrays/12.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Javascript 按属性获取存储在MongoDB中的数组_Javascript_Arrays_Node.js_Mongodb_Express - Fatal编程技术网

Javascript 按属性获取存储在MongoDB中的数组

Javascript 按属性获取存储在MongoDB中的数组,javascript,arrays,node.js,mongodb,express,Javascript,Arrays,Node.js,Mongodb,Express,存储在my 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", "n

存储在my 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
,一个对象具有与3相同的
age
。我想通过
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
进行查询?

您应该在带有
age
字段的筛选文档中参考并使用它。请阅读此链接以了解更多信息

您可以使用“在
查找后添加”对即将到来的数据进行排序

Property.find({ age: { $eq: req.params.age } }).sort({ _id: -1 })
在sort参数中指定要排序的一个或多个字段,值为1或-1分别指定升序或降序排序

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