Properly close mongoose's connection once you're done

后端 未结 7 765
没有蜡笔的小新
没有蜡笔的小新 2020-12-07 17:20

I\'m using mongoose in a script that is not meant to run continuously, and I\'m facing what seems to be a very simple issue yet I can\'t find an answer; simply put once I ma

7条回答
  •  借酒劲吻你
    2020-12-07 17:43

    Just as Jake Wilson said: You can set the connection to a variable then disconnect it when you are done:

    let db;
    mongoose.connect('mongodb://localhost:27017/somedb').then((dbConnection)=>{
        db = dbConnection;
        afterwards();
    });
    
    
    function afterwards(){
    
        //do stuff
    
        db.disconnect();
    }
    

    or if inside Async function:

    (async ()=>{
        const db = await mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: 
                      true })
    
        //do stuff
    
        db.disconnect()
    })
    

    otherwise when i was checking it in my environment it has an error.

提交回复
热议问题