如何写一个返回Promise的mongodb插入动作?
发布于 3 年前 作者 ilovelll 4167 次浏览 来自 问答

自己写代码写着玩,把callback形式的module改成了Promise的方式,但是执行一直报这个错误 name: 'MongoError', message: 'topology was destroyed' }, 遂来这里请教

贴代码如下:

const getConn = new Promise((resolve, reject) => {
    MongoClient.connect(url, (err, db) => {
        if (err) reject(new Error('数据库连接出错'))
        resolve(db)
    })
})

exports.insertDoc = data => {
    return new Promise((resolve, reject) => {
        getConn.then(db => {
            let collection = db.collection('meizitu')
            collection.insertOne(data, (err, result) => {
                if (err) {
                    if (err.code == 11000) {
                        result = { ok: -1, msg: "数据库已抓取,请勿重复抓取" }
                    } else {
                        console.log("数据库插入出错: ", err)
                        result = { ok: -1, msg: "DB ERROR!" }
                    }
                }
                db.close()
                result.result ? resolve(result.result) : resolve(result)
            })
        }).catch(err =>{
            console.log(err)
        })
    })
2 回复

附加信息: 1. 这个insertDoc() 有多进程执行,并且根据返回信息会重复执行(就是开多个线程,每个线程顺序执行多个任务)。

  1. 如果把db.close()注释掉就不报错了。
  2. 何时关闭db.close()较好?
MongoClient connection pooling
A Connection Pool is a cache of database connections maintained by the driver so that connections can be re-used when new connections to the database are required. To reduce the number of connection pools created by your application, we recommend calling MongoClient.connect once and reusing the database variable returned by the callback:

var express = require('express');
var mongodb = require('mongodb');
var app = express();

var MongoClient = require('mongodb').MongoClient;
var db;

// Initialize connection once
MongoClient.connect("mongodb://localhost:27017/integration_test", function(err, database) {
  if(err) throw err;

  db = database;

  // Start the application after the database connection is ready
  app.listen(3000);
  console.log("Listening on port 3000");
});

// Reuse database object in request handlers
app.get("/", function(req, res) {
  db.collection("replicaset_mongo_client_collection").find({}, function(err, docs) {
    docs.each(function(err, doc) {
      if(doc) {
        console.log(doc);
      }
      else {
        res.end();
      }
    });
  });
});

官方也不推荐关

回到顶部