Reputation: 5104
Here is my code:
var environment = "ClientUnitTests";
//set up mongodb
var Db = require('mongodb').Db,
MongoClient = require('mongodb').MongoClient,
Server = require('mongodb').Server,
ReplSetServers = require('mongodb').ReplSetServers,
ObjectID = require('mongodb').ObjectID,
Binary = require('mongodb').Binary,
GridStore = require('mongodb').GridStore,
Grid = require('mongodb').Grid,
Code = require('mongodb').Code,
BSON = require('mongodb').pure().BSON,
assert = require('assert');
var db = new Db('test',new Server('localhost',27017),{safe:true});
db.open(function(err, db) {
assert.equal(null, err);
});
var users = db.collection("users");
//Clean up data in test database for clientUnit tests
if (environment == "ClientUnitTests") {
users.remove({},function(err,numberRemoved){
console.log("inside remove call back" + numberRemoved);
});
}
Basically I'm trying to delete all the data from my users collection when the app starts up in the 'ClientUnitTests' mode. Unfortunately the console.log statement never fires (also verified by setting a breakpoint there that never fires).
What am I doing wrong for removing all documents in this collection?
Upvotes: 1
Views: 6812
Reputation: 5104
(doh moment)
Node is an asynchronous environment. This means that the database connection isn't open when I'm trying to call remove and also the reason why the rest of my requests work (they come seconds to minutes later rather than miliseconds).
For completeness here is an example that utilizes the callback to ensure remove happens based on my environment variable:
db.open(function(err, db) {
assert.equal(null, err);
if (environment == "ClientUnitTests") {
db.collection("users").remove({},function(err,numberRemoved){
console.log("inside remove call back" + numberRemoved);
});
}
});
Upvotes: 3