1

Hello I am new in mongoose , express and I want to GET a particular key value from all the object of a document array and show in response.

I have following data in a document.

[{
    "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
}]

I want to get list of all companyID from the document. How can I query this ?

I tried this in route but getting empty response:-

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

How can I get list of companyIDs ?

NoobCoder
  • 493
  • 8
  • 25

1 Answers1

3

you have to map the output

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

or you can change your query to select only companyID field from collection

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

see more here about select specific columns: Mongoose, Select a specific field with find

Saurabh Mistry
  • 12,833
  • 5
  • 50
  • 71