Andy
Andy

Reputation: 161

how to promisify the mongoDB with the util's promisify function?

I want to use the promisify with the MongoDB. I try the code at last, the connect is OK, but the function insertOne not. Could anyone help me out? And it is better to explain why, and what is a context when with '.db().collection()', how should I make the function promisify with the code like:

a().b().c().d()

and here is my code like bellow.

import "babel-polyfill"
const mongoClient = require('mongodb').MongoClient
const util = require('util')
const chalk = require('chalk')

const url = 'mongodb://localhost:27017'
const dbName = ''
const collName = ''

let connect = util.promisify(mongoClient.connect).bind(mongoClient)
let insertOne = util.promisify(mongoClient.insertOne)
                .bind(mongoClient)

const main = async () => {
    try {
        await connect(url)
        insertOne({a100: 1}).db(dbName).collection(collName)
    } catch (err) {
        console.log(chalk.red(err.toString()))
    }

    mongoClient.close()
}    

main()

Upvotes: 2

Views: 1030

Answers (1)

tfogo
tfogo

Reputation: 1436

The MongoDB driver already returns promises (see the documentation). You don't need to use util.promisify. Also, you don't chain db and collection on queries like insertOne. It's the other way round.

For example:

 client = await mongoClient.connect(url)
 client.db(dbName).collection(collName).insertOne({a100: 1})

(NB if you're using the old mongodb node driver version 2.2 it's slightly different as connect returns a db object - documentation for 2.2)

Upvotes: 3

Related Questions