Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Mongoose Model.find() hangs when not connected to database

I'm going through a few error scenarios, trying to understand how to handle those.

In the case where there is no database connection, a Mongoose Model.find(...) call seems to hang. Below the example code. I would have assumed that the callback is invoked with an err object, but it is not.

How can I prevent the model call to hang? Do I manually have to check the readyState each time I access a model?

// app.js
// Let's use a non-existing host so connecting fails:
// (callback is invoked with err object)
mongoose.connect('mongodb://localhostXXX/blog', function(err){ ... });

BlogPost  = mongoose.model('BlogPost', BlogPostSchema);

// api.js
exports.list_posts = function(req, res) {

    // Ready state is '0' = disconnected (since we used a wrong hostname)   
    console.log('DB ready state: ' + BlogPost.db.readyState);

    // This will not invoke the callback:
    BlogPost.find(function(err, threads) {
        // Never called...
    });
 }
like image 701
Mark Avatar asked Jul 23 '12 07:07

Mark


People also ask

How does find work in Mongoose?

The find() function is used to find particular data from the MongoDB database. It takes 3 arguments and they are query (also known as a condition), query projection (used for mentioning which fields to include or exclude from the query), and the last argument is the general query options (like limit, skip, etc).

What does model find return in Mongoose?

The Model. find() function returns an instance of Mongoose's Query class. The Query class represents a raw CRUD operation that you may send to MongoDB. It provides a chainable interface for building up more sophisticated queries.

Does find return an array Mongoose?

Return valueThe returned value could be an array of documents, a single document if it matches only one, or an empty array if no document is matched.

Do you need to close Mongoose connection?

You should close a mongoose connection when a Node POSIX signal is happening. SIGINT process is triggered when Ctrl-C has been pressed on terminal or a server shutdown. Another possible scenario is to close a connection when a data streaming is done.


1 Answers

It is not an answer, but hope it will help you to find solution. Had very similar issue with mongoose.createConnection while using passport module, found out that it works fine with mongoose.connect

like image 71
bFunc Avatar answered Oct 19 '22 04:10

bFunc