This sounds legit to me :
1°) you open a connection
2°) when it's open you send a query
3°) when you've got you results, you process them and close the
connection
What you attempted causes indeed a race condition problem because of the
asynchronous nature of javascript.
What is the problem with putting the close() statement there ?
If you don't like it because of the many anonymous nested functions, you
could rather use references :
var Query = new Class({
Extends: Events,
initialize: function( collectionName, searchKey ){
this.collectionName = collectionName;
this.searchKey = searchKey;
},
run: function(){
this.addEvent( 'db_ready', this.execute.bind( this ) );
this.connection = connection.open( function( err, client ){
this.fireEvent( 'db_ready', [ err, client ] );
}.bind( this ));
},
execute: function( err, client ){
var collection;
if (err) throw err;
collection = mongo.Collection( client, this.collectionName );
collection.find( this.searchKey ).toArray( this.process.bind( this
));
},
process: function( err, nodes ){
this.fireEvent( 'data', [ nodes ] );
this.connection.close();
}
});
var query = new Query( collectionName, searchKey );
query.addEvent( 'data', doSomething );
query.run();
If you use node.js, you'll probably have to get used to such function
referencing, since almost everything is asynchronous :)
Le samedi 07 avril 2012 à 00:11 -0400, Matthew Hazlett a écrit :
> 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?