How to transform the asynchronous mongodb query function into the form of Promise?

  node.js, question

I can understand all the examples in the book in learning ES6 Promise recently, but it cannot be applied to actual development. Can anyone take mongodb’s asynchronous query as an example to illustrate how to apply Promise?
The sample code is as follows:

function getOne(route,callback) {
 mongodb.open(function(err,db) {
 if (err) {
 mongodb.close();
 return callback(err);
 };
 db.collection('posts',function(err,collection) {
 if (err) {
 mongodb.close();
 return callback(err);
 };
 collection.findOne({
 route:route,
 },function(err,doc) {
 mongodb.close();
 if (err) {
 return callback(err);
 };
 if (doc){
 callback(null,doc);
 } else {    //if page not found
 callback('404');
 bracket
 
 });
 });
 });
 };

For example, this code, how to transform it into Promise form? Thank you!

First, abstract your code into three different functions:

var openDB = function() {
 return new Promise(function(resolve, reject) {
 mongodb.open(function(err, db) {
 if (err) {
 mongodb.close();
 return reject(err);
 bracket
 resolve(db);
 });
 });
 };
 
 var getPosts = function(db) {
 return new Promise(function(resolve, reject) {
 db.collection('posts', function(err, collection) {
 if (err) {
 mongodb.close();
 return reject(err);
 bracket
 resolve(collection);
 });
 });
 };
 
 var insertPost = function(collection) {
 return new Promise(function(resolve, reject) {
 collection.insert(post, {safe: true}, function(err) {
 mongodb.close();
 if (err) {
 return reject(err);
 bracket
 resolve(null);
 });
 });
 };

Then, when using them, the chain call, combined together is your result:

openDB()
 .then(function(db) {
 return getPosts(db);
 })
 .then(function(collection) {
 return insertPost(collection, post);
 })
 .catch(function(err) {
 console.log(err);  //error is captured here
 });