Reputation: 1043
Mongoose shows a strange behavior. The following lines of code first delete a collection entirely, then create a new object, and finally delete the collection again.
Model.remove().exec();
var obj = new Model({ name: 'my object' });
obj.save();
Model.remove().exec();
While the first delete works (each time I start the program, the collection is emptied), the second has no effect (when I query the collection, the object is still there). I am at a loss to understand what is going on here.
Environment: Node.js v0.8.20, MongoDB v1.2.14 and Mongoose v3.6.0
Upvotes: 0
Views: 2161
Reputation: 883
I have this piece of code which does is executed at the end of my tests;
var clearDb = function (){
// Reset collections
ProjectModel.remove().exec()
.then(function() {
console.log('Removed collection: Project');
});
};
however, its not clearing the collection! It works in another test cases which is a different model and that works! Any ideas? I can see the log
Upvotes: 2
Reputation: 146014
You need to use callbacks to get serial operations. All I/O in node.js is asynchronous. What this means is probably your .save()
is slower than the .remove().exec()
so the 2nd .remove().exec()
completes and then the save happens. You need to use the callback functions to do proper flow control. The deeply nested callback (AKA callback hell) way looks like this, but using more named functions or a flow control library like async.js will solve that.
Model.remove().exec(function (error) {
var obj = new Model({ name: 'my object' });
obj.save(function (error) {
Model.remove().exec();
});
});
Feel free to throw in some error handling there as well.
Upvotes: 5