Skip to content

Instantly share code, notes, and snippets.

@Tug
Created November 21, 2012 10:51
Show Gist options
  • Save Tug/4124267 to your computer and use it in GitHub Desktop.
Save Tug/4124267 to your computer and use it in GitHub Desktop.
Mongoose : objects not found after synchronous saves
var mongoose = require('mongoose');
var File = new mongoose.Schema({
servername : { type: String, index: { unique: true } }
, originalname : String
});
var FileModel = mongoose.model('File', File);
function connect(callback) {
mongoose.connect("mongodb://localhost:27017/test-inserts", function(err) {
if(err) {
console.log(err);
return;
}
console.log(err || "Connected to MongoDB");
callback();
});
}
function success(doc) {
console.log("success!", doc);
}
function error(err) {
console.log("ERROR! ",err.message);
}
connect(function() {
FileModel.remove({}, function(err) {
if(err) {
error(err || new Error('Error emptying collection'));
return;
}
for(var i=0;i<10;i++) {
var file = new FileModel({servername: "hello"+i, originalname: "world"+i});
file.save(function(serr) {
FileModel.findOne({servername: "hello"+i}, function(err, doc) {
if(err || !doc) {
error(err || new Error('File not found'));
return;
}
success(null, doc);
});
});
}
});
});
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment