Properly close mongoose's connection once you're done

后端 未结 7 759
没有蜡笔的小新
没有蜡笔的小新 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:37

    I'm using version 4.4.2 and none of the other answers worked for me. But adding useMongoClient to the options and putting it into a variable that you call close on seemed to work.

    var db = mongoose.connect('mongodb://localhost:27017/somedb', { useMongoClient: true })
    
    //do stuff
    
    db.close()
    
    0 讨论(0)
  • 2020-12-07 17:40

    You will get an error if you try to close/disconnect outside of the method. The best solution is to close the connection in both callbacks in the method. The dummy code is here.

    const newTodo = new Todo({text:'cook dinner'});
    
    newTodo.save().then((docs) => {
      console.log('todo saved',docs);
      mongoose.connection.close();
    },(e) => {
      console.log('unable to save');
    });
    
    0 讨论(0)
  • 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.

    0 讨论(0)
  • 2020-12-07 17:48

    You can close the connection with

    mongoose.connection.close()
    
    0 讨论(0)
  • 2020-12-07 17:50

    Probably you have this:

    const db = mongoose.connect('mongodb://localhost:27017/db');
    
    // Do some stuff
    
    db.disconnect();
    

    but you can also have something like this:

    mongoose.connect('mongodb://localhost:27017/db');
    
    const model = mongoose.model('Model', ModelSchema);
    
    model.find().then(doc => {
      console.log(doc);
    }
    

    you cannot call db.disconnect() but you can close the connection after you use it.

    model.find().then(doc => {
      console.log(doc);
    }).then(() => {
      mongoose.connection.close();
    });
    
    0 讨论(0)
  • 2020-12-07 17:52

    You can set the connection to a variable then disconnect it when you are done:

    var db = mongoose.connect('mongodb://localhost:27017/somedb');
    
    // Do some stuff
    
    db.disconnect();
    
    0 讨论(0)
提交回复
热议问题