首页 > express+mongodb开发报错 server instance in invalid state undefined

express+mongodb开发报错 server instance in invalid state undefined

问题:
问题如标题所示,当前端同时向后台请求两个需要操作数据的接口时,后台就报错了,感觉是因为第二次请求时前一次数据库还没有关闭导致报错。

代码如下:
db.js:

var settings = require('../settings'),

Db = require('mongodb').Db,
Connection = require('mongodb').Connection,
Server = require('mongodb').Server;

module.exports = new Db(settings.db, new Server(settings.host, settings.port), {safe: true});
user.js

user.checkCollect = function(username, artid, callback) {

mongodb.collection('users', function (err, collection) {
    if (err) {
      mongodb.close();
      return callback(true);
    }
    collection.findOne({
      "name": username
    }, function(err, post) {
      
      if (err) {
        mongodb.close();
        return callback(err);
      }
      if (!post) {
        mongodb.close();
        return callback(true);
      }
      var userCollections = post.collections
        , hasCollected = false
        ;
      for (var i = 0, len = userCollections.length; i < len; i++) {
        if (userCollections[i] === artid) {
          hasCollected = true;
          break;
        }
      }
      callback(false, hasCollected);
      mongodb.close();
    })
  })
}

}
这是数据库操作的代码,经过测试,发现无论请求的是同一个接口还是不同的接口,只要同时请求两次以上,都会出现这个问题,求大牛指教!


看起来你用的是node-mongodb-native驱动。老版本确实有使用过DB作为顶级对象,不过现在的驱动通常建议把MongoClient用为顶级对象使用。直接参考驱动文档:
https://github.com/mongodb/no...
注意MongoClient维护着连接池,所以通常当你的应用退出前都可以不要关闭,保留一个单例的MongoClient一直用就可以了。

【热门文章】
【热门文章】