MongoDB
 SQL >> Database >  >> NoSQL >> MongoDB

Avvolgere MongoDB find().toArray() in una Promise

Se una query MongoDB in Node.js sembra non restituire nulla, avvolgi la chiamata al driver basata su callback in una Promise per rendere esplicito il flusso di controllo.

function getUsers() { return new Promise(function(resolve, reject) { database.collection("customers").find().toArray(function(err, docs) { if (err) { return reject(err); } return resolve(docs); }); }); }

In questo modo gli errori sono più facili da gestire e la funzione può essere usata con async/await.