如何使用猫鼬获取文档的特定键值

How to get particular key value of a document using mongoose

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

我在文档中有以下数据。

[{
    "admins": {
        "email": "rrg_gg@infomail.com",
        "password": "a$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": "aM5GDh.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);
  });
});

如何获取公司 ID 列表?

你必须映射输出

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

或者您可以将查询更改为仅 select 来自集合

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

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