2017-10-02 5 views
0

lodash a une fonction nommée keyby https://lodash.com/docs/4.17.4#keyBy comment obtenir le résultat comme ça?Comment recevoir le résultat en tant que "keyBy" d'un objet au lieu d'un tableau à partir d'une requête mongo?

const data = db.collection.find() 


[ 
    { id: 'a', text: 'text' }, 
    { id: 'b', text: 'text' }, 
    { id: 'c', text: 'text' }, 
    { id: 'd', text: 'text' }, 
    { id: 'e', text: 'text' }, 
] 

lodash.keyBy(data, 'id') 

{ 
    a: { id: 'a', text: 'text' }, 
    b: { id: 'b', text: 'text' }, 
    c: { id: 'c', text: 'text' }, 
    d: { id: 'd', text: 'text' }, 
    e: { id: 'e', text: 'text' }, 
} 

Répondre

0

Vous ne pouvez pas obtenir l'objet dans la requête de recherche dans MongoDB. Mais, vous pouvez construire un en utilisant lodash « keyBy »

const data = db.collection.find({}, function(err,results){ 
    if(err) throw err; 
     return lodash.keyBy(results, 'id'); 
}); 
+0

cadre si l'agrégation ne peut pas le faire? Je dois tirer les disques d'abord puis keyby il – crapthings

+0

@crapthings oui –