【问题标题】:How to get particular key value of a document using mongoose如何使用猫鼬获取文档的特定键值
【发布时间】:2019-10-16 23:58:09
【问题描述】:

您好,我是 mongoose 的新手,表示我想 GET 来自文档数组的所有对象的特定键值并在响应中显示。

我在文档中有以下数据。

[{
    "admins": {
        "email": "rrg_gg@infomail.com",
        "password": "$2a$10$VNS6RraM5GDh.EU/KJuVle8Qjntog0eSPW3Zup6XDvlDR25Jor/56",
        "firstName": "hjjh",
        "lastName": "ZY",
    },
    "_id": "5cefa5d0531e6b597dceb6d0",
    "companyName": "XYZ",
    "address": "World",
    "contactDetails": "54534454",
    "companyID": "044025",
    "__v": 0
},
{
    "admins": {
        "email": "beans-gg@merok.com",
        "password": "$2a$10M5GDh.EU/KJuVle8Qjntog0eSPWDR25Jor/56",
        "firstName": "gg",
        "lastName": "yu",
    },
    "_id": "5cefa5d0531e6b5678dceb6e8",
    "companyName": "gY",
    "address": "World",
    "contactDetails": "534454",
    "companyID": "984556",
    "__v": 0
}]

我想从文档中获取所有companyID 的列表。这个怎么查询?

我在路由中尝试过,但得到空响应:-

 router.get('/getCid', function(req, res, next){
    Admin.find({}, function(err, admin) {
    res.json(admin.companyID);
  });
});

如何获取 companyID 列表?

【问题讨论】:

    标签: node.js mongoose routes mongoose-schema


    【解决方案1】:

    你必须映射输出

    router.get('/getCid', function(req, res, next){
        Admin.find({}, function(err, data){
        let companyIDS = data.map((admin)=>{return admin.companyID});
        res.json(companyIDS);
      });
    });
    

    或者您可以将查询更改为仅从集合中选择 companyID 字段

     router.get('/getCid', function(req, res, next){
            Admin.find({},'companyID',function(err, data){
            res.json(data);
          });
        });
    

    在此处查看有关选择特定列的更多信息:Mongoose, Select a specific field with find

    【讨论】:

      猜你喜欢
      • 2018-10-13
      • 2020-07-25
      • 1970-01-01
      • 2016-07-30
      • 1970-01-01
      • 2020-08-10
      • 2017-11-24
      • 2013-04-16
      • 2020-09-14
      相关资源
      最近更新 更多