使用 mongodb-memory-server 和 mongoose 创建内存数据库

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

我想使用 mongodb-memory-server 和 mongoose 创建一个内存数据库。谁能告诉我正确的方法。

阅读文档 here 并遇到以下解决方案。

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;