【问题标题】:Get array stored in MongoDB by property通过属性获取存储在 MongoDB 中的数组
【发布时间】: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


    【解决方案1】:

    您应该参考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 })
    

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

    【讨论】:

      猜你喜欢
      • 2019-06-25
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2018-05-03
      • 1970-01-01
      • 1970-01-01
      • 2017-08-24
      相关资源
      最近更新 更多