If the problem is cleaning up after an error occurs then change your if
(err) statement to include the cleanup of the connection like so:
collection.find(searchKey).toArray(function(err, nodes) {
if (err) {
connection.close();
throw err;
}
this.emit('data', nodes);
connection.close();
}.bind(this));
and you can do this anywhere you get back an err object - like in the
function you pass to connection.open. And kik is right that this is a
pattern you should get used to seeing in node.
Jon
On Friday, April 6, 2012 9:11:24 PM UTC-7, hazlema wrote:
>
> I asked my question in the mongodb forum, but didn't get an answer. I
> figure someone here may be able to tell me whats wrong
>
> I have the following function in Node (I'm using the mootools server
> side library):
>
> query: function(collectionName, searchKey) {
> connection.open(function(err, client) {
> if (err) throw err;
> collection = mongo.Collection(client, collectionName);
> collection.find(searchKey).toArray(function(err, nodes) {
> this.emit('data', nodes);
> connection.close();
> }.bind(this));
> }.bind(this));
> }
>
> It works just fine, however, I want to put the connection.close() line
> at the bottom of the function instead of in the collection.find block
> (in case theirs an error with the database or something). Problem is
> when I do that the database gets closed before the query. I think its
> happening because of the async model node uses. Is there a way to get
> around this issue?
>
>