简体   繁体   中英

Mongodb find() method freezes over Nodejs

I'm starting webapps development with Node, so I'm quite new with this technology.

I've done several examples and managed to make it run.

However, now I'm trying to use Mongodb but I'm not able to make it run properly. It seems that the connection is working but when I call the find() method and I go to localhost:3000/near (which is the url that makes the findAll docs), the browser spends about a half a minute loading and finishes returning nothing ( ERR_EMPTY_RESPONSE ).

This is my code:

app.js

app.get('/near', function(req, res){
    server.findAll( function(error,docs){
        res.render('near', { 
                title: 'Cerca tuyo!',
                places:docs
        });
    })
});

And this my Server.js

//constructor
AppServer = function(host, port) {
  this.db= new Db('node-mongo-places', new Server(host, port, {safe: false}, {auto_reconnect: true}, {}));
  this.db.open(function(){});
};

//Devuelve la colección de "places"
AppServer.prototype.getCollection= function(callback) {
  this.db.collection('places', function(error, places_collection) {
    if( error ) callback(error);
    else callback(null, places_collection);
  });
};


//Devuelve todos los contenidos de la DB places
AppServer.prototype.findAll = function(callback) {
    this.getCollection(function(error, places_collection) {
      if( error ) callback(error)
      else {
        places_collection.find().toArray(function(error, results) {
          if( error ) callback(error)
          else callback(null, results)
        });
      }
    });
};

I have debugged the code writing console.log() and it seems that it does not reach to the callback function from places_collection.find().toArray(function(error, results) {

Any idea why the server does not return anything?


!!! EDIT:

I found some piece of code to test if the connection to mongodb is alright and it says that it's not: [Error: failed to connect to [localhost:27017]]

So the problem is in the connection. Should I run mongodb first? I thought that the app.js itself would did that for me!

Got the answer for this question:

As said, I thought that npm install mongodb would install the whole thing. However, it does not, so I managed to fix it by executing sudo apt-get install mongodb .

Once installed, the app itself runs mongodb.

I added this to my mongodb open() method so as I could see what was happening:

this.db.open(function(error,db){
    if(error) {
        console.log(error);
    } else {
        console.log("connected to mongod with no problems...");
    }
  });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM