带有MongoDB的NodeJS在find()方法中冻结

时间:2013-07-09 19:18:06

标签: node.js mongodb

我正在通过构建一个非常简单的pastebin来学习NodeJS。只要我不尝试使用MongoDB保存数据,代码就可以工作。

尝试打开“全部列出”页面时,应用会冻结。

我把问题归结为代码的这一部分,

HoldText = function(){
    this.db = new Db('name', new Server('localhost', 27017, {auto_reconnect: true}, {}), {safe: false});
    this.db.open(function(){});
};

HoldText.prototype.getCollection = function(callback) {
    this.db.collection('texts', function(error, text_collection) {
            if (error) callback(error);
            else callback(null, text_collection);
    });
};


HoldText.prototype.findAll = function(callback) {
    console.log("FLAG0");
    this.getCollection(function(error, text_collection) {
            if (error) {
                    callback(error);
                    console.log("FLAG 1");
            }
            else { 
                    console.log("FLAG 2");
                    text_collection.find().toArray(function(error, results) {
                            if( error ) { 
                                    console.log("FLAG3");
                                    callback(error);
                            } else {
                                    console.log("FLAG4");
                                    callback(null, results);
                            }
                            console.log("FLAG5");
                    });
            }
    });
};
console.log("FLAG6");

标记0,2和6被调用。 有人对我有任何建议吗?

1 个答案:

答案 0 :(得分:0)

我不会声称这是最佳做法。事实上,我认为我的addAdminUser功能是完全无用的。但是当我写这篇文章时,我不知道自己在做什么。搬到猫鼬是一个很好的决定。但这是我用于spendmycents.com的DatabaseController。收集有关如何打开与mongo的连接的内容。

'use strict';

var DatabaseController = (function() {
  var mongo = require('mongodb');
  var logger = require('winston');
  var openConnectionToCollection;
  var getOrCreateClient;
  var deleteObjectByQuery;

  getOrCreateClient = function(callback) {
    var server = new mongo.Server(process.env.OPENSHIFT_MONGODB_DB_HOST, process.env.OPENSHIFT_MONGODB_DB_PORT, {auto_reconnect: false});
    var username = process.env.OPENSHIFT_MONGODB_DB_USERNAME;
    var password = process.env.OPENSHIFT_MONGODB_DB_PASSWORD;
    var finishClientSetup, addAdminUser, authenticateToClient;

    var client = new mongo.Db(process.env.OPENSHIFT_MONGODB_DB_NAME, server, {w: 1, strict: true});

    logger.info('Client created');

    client.open(function(error, openedClient) {
      logger.info('Client opened');
      if (error) {
        throw error;
      }
      finishClientSetup(openedClient);
    });

    finishClientSetup = function(openedClient) {
      var usersCollection = new mongo.Collection(openedClient, 'system.users');
      logger.info('Looking for users in system.users');
      usersCollection.findOne({user: username}, function(error, doc) {
        if (error) {
          logger.warn('Error finding user in system.users!');
          logger.error(error);
          throw error;
        }
        if (!doc) {
          addAdminUser(openedClient);
        } else {
          authenticateToClient(openedClient);
        }
      });
    };

    addAdminUser = function(openedClient) {
      logger.info('No user found. Adding user.');
      openedClient.addUser(username, password, function(error, result) {
        if (!result || error) {
          logger.warn('Error adding admin user to client!');
          logger.error(error);
          throw 'Error adding admin user to client! ' + error;
        }
        authenticateToClient(openedClient);
      });
    };

    authenticateToClient = function(openedClient) {
      logger.info('Authenticating to client');
      openedClient.authenticate(username, password, function(error, result) {
        logger.info('Closing client');
        openedClient.close();
        if (result && !error) {
          logger.info('Success authenticating');
          callback(error, openedClient);
        } else {
          logger.warn('Failure in authenticating!');
          logger.error(error);
          throw 'Authentication to database failed! ' + error;
        }
      });
    };
  };

  openConnectionToCollection = function(collectionName, callback) {
    if (!collectionName) {
      throw 'collectionName must be defined!';
    }
    getOrCreateClient(function(error, receivedClient) {
      if (error) {
        throw error;
      }
      receivedClient.open(function(error, openedClient) {
        if (error) {
          callback(error, null);
        } else {
          callback(new mongo.Collection(openedClient, collectionName));
        }
      });
    });
  };

  deleteObjectByQuery = function(collectionName, query, callback) {
    openConnectionToCollection(collectionName, function(collection) {
      collection.remove(query, {save: true}, function(error, numberRemoved) {
        collection.db.close();
        callback(error, numberRemoved);
      });
    });
  };

  return {
    findAll: function(collectionName, callback) {
      openConnectionToCollection(collectionName, function(collection) {
        collection.find().toArray(function(error, docs) {
          collection.db.close();
          callback(error, docs);
        });
      });
    },
    saveObject: function(collectionName, object, callback) {
      openConnectionToCollection(collectionName, function(collection) {
        collection.save(object, {safe: true}, function(error, doc) {
          collection.db.close();
          callback(error, doc);
        });
      });
    },
    findOneObjectById: function(collectionName, idString, callback) {
      this.findOneObjectByQuery(collectionName, {_id: new mongo.ObjectID(idString)}, callback);
    },
    findOneObjectByQuery: function(collectionName, query, callback) {
      openConnectionToCollection(collectionName, function(collection) {
        collection.findOne(query, function(error, doc) {
          collection.db.close();
          callback(error, doc);
        });
      });
    },
    deleteObjectById: function(collectionName, idString, callback) {
      deleteObjectByQuery(collectionName, {_id: new mongo.ObjectID(idString)}, callback);
    }
  };
})();

module.exports = DatabaseController;