javascriptmongoosein-memory-database

Create in-memory database using mongodb-memory-server and mongoose


I want to create a in-memory database using mongodb-memory-server and mongoose. Can anyone show the correct way to do it.


Solution

  • Read the documentation here and came accross the following solution.

    const mongoose = require('mongoose');
    const { MongoMemoryServer } = require('mongodb-memory-server');
    
    const mongoServer = new MongoMemoryServer();
    
    mongoose.Promise = Promise;
    mongoServer.getUri().then((mongoUri) => {
      const mongooseOpts = {
        useNewUrlParser: true,
        useFindAndModify: false,
        useCreateIndex: true,
        useUnifiedTopology: true,
      };
    
      mongoose.connect(mongoUri, mongooseOpts);
    
      mongoose.connection.on('error', (e) => {
        console.log(e);
      });
    
      mongoose.connection.once('open', () => {
        console.log(`MongoDB successfully connected to ${mongoUri}`);
      });
    });
    module.exports=mongoose.connection;