您好,我是mongoose的新手,express,我想从文档数组的所有对象中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);
});
});
如何获取公司ID列表?
答案 0 :(得分: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