Keeping open a MongoDB database connection

前端 未结 3 1010
醉话见心
醉话见心 2020-12-07 22:14

In so many introductory examples of using MongoDB, you see code like this:

var MongoClient = require(\'mongodb\').MongoClient;
MongoClient.connect(\"mongodb:         


        
3条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-07 22:33

    mongodb version ^3.1.8

    Initialize the connection as a promise:

    const MongoClient = require('mongodb').MongoClient
    const uri = 'mongodb://...'
    const client = new MongoClient(uri)
    const connection = client.connect() // initialized connection
    

    And then call the connection whenever you wish you perform an action on the database:

        // if I want to insert into the database...
        const connect = connection
        connect.then(() => {
            const doc = { id: 3 }
            const db = client.db('database_name')
            const coll = db.collection('collection_name')
            coll.insertOne(doc, (err, result) => {
                if(err) throw err
            })
        })
    

提交回复
热议问题