首页 > 解决方案 > 在 Node.js 中共享 mongodb 连接时遇到问题

问题描述

我正在尝试编写一个服务来管理 mongodb 连接。我希望连接打开一次然后重复使用:

const MongoClient = require('mongodb').MongoClient;

// Port it always 27017
const url = 'mongodb://localhost:27017';

// The database name
const dbName = 'mongo-crud';

let db = null;

// Gets an instance of the db
module.exports.getDB = () => new Promise((resolve, reject) => {
  if (db) {
    console.log('already got the db');
    resolve(db);
    return;
  }

  MongoClient.connect(url, { useUnifiedTopology: true })
  .then(client => {
    console.log('make a new client');
    db = client.db(dbName);
    resolve(db);
  })
  .catch(error => {
    reject(error);
    process.exit(1);
  })
});

我在我的App.js

const client = require('./MongoDBService');


client.getDB()
 .then(db => console.log('database connected'))
 .catch(error => console.log(error));

client.getDB()
  .then(db => db.collection('dogs'))
  .then(collection => collection.find().toArray())
  .then(array => console.log(array))
  .catch(error => console.error(error));

client.getDB()
  .then(db => db.collection('cats'))
  .then(collection => collection.find().toArray())
  .then(array => console.log(array))
  .catch(error => console.error(error));

当我检查控制台日志时,它似乎每次都在创建一个新实例"make a new client",为什么我会在db这里丢失对象?

标签: javascriptnode.jsmongodb

解决方案


尝试在异步函数中运行它并等待它

const client = require('./MongoDBService');

async function init () {
  await client.getDB()
   .then(db => console.log('database connected'))
   .catch(error => console.log(error));

  await client.getDB()
    .then(db => db.collection('dogs'))
    .then(collection => collection.find().toArray())
    .then(array => console.log(array))
    .catch(error => console.error(error));

  await client.getDB()
    .then(db => db.collection('cats'))
    .then(collection => collection.find().toArray())
    .then(array => console.log(array))
    .catch(error => console.error(error));
}

init()

但是您也可以将它们全部放在一个承诺链中

const client = require('./MongoDBService');

client.getDB()
 .then(db => console.log('database connected'))
 .catch(error => console.log(error))

 .then(client.getDB())
 .then(db => db.collection('dogs'))
 .then(collection => collection.find().toArray())
 .then(array => console.log(array))
 .catch(error => console.error(error));

 .then(client.getDB())
 .then(db => db.collection('cats'))
 .then(collection => collection.find().toArray())
 .then(array => console.log(array))
 .catch(error => console.error(error));

当你玩完之后,你绝对应该使用 async/await

const client = require('./MongoDBService');

async function dbStuff () {
  const db = await client.getDB()
  console.log('database connected')

  const dogsCollection = db.collection('dogs')
  const array = await dogsCollection.find().toArray()
  console.log(array)

  const catsCollection = db.collection('cats'))
  const catsArray = await catsCollection.find().toArray()
  console.log(catsArray)
}


const init = async () => {
  try {
    await doStuff()
  } catch(error) {
    console.error(error)
  }
}

init()
// OR
// doStuff().catch(error => console.error(error));



推荐阅读