Permalink
Browse files

Pass a third argument of `created` to the callback to determine if th…

…e document was created or not from our call
  • Loading branch information...
drudge committed Nov 13, 2012
1 parent 29812a2 commit 73d2cb4045f8a9c2536c96275c6174deecfcded7
Showing with 24 additions and 7 deletions.
  1. +4 −2 README.md
  2. +5 −3 index.js
  3. +15 −2 test/index_test.js
View
@@ -20,9 +20,11 @@ var Click = mongoose.model('Click', ClickSchema);
The Click model now has a findOrCreate static method
```javascript
-Click.findOrCreate({ip: '127.0.0.1'}, function(err, click) {
+Click.findOrCreate({ip: '127.0.0.1'}, function(err, click, created) {
+ // created will be true here
console.log('A new click from "%s" was inserted', click.ip);
- Click.findOrCreate({}, function(err, click) {
+ Click.findOrCreate({}, function(err, click, created) {
+ // created will be false here
console.log('Did not create a new click for "%s"', click.ip);
})
});
View
@@ -23,18 +23,20 @@ function findOrCreatePlugin(schema, options) {
if(err || result) {
if(options && options.upsert && !err) {
self.update(conditions, doc, function(err, count){
- self.findOne(conditions, callback);
+ self.findOne(conditions, function(err, result) {
+ callback(err, result, false);
+ });
})
} else {
- callback(err, result)
+ callback(err, result, false)
}
} else {
for (var key in conditions) {
doc[key] = conditions[key];
}
var obj = new self(conditions)
obj.save(function(err) {
- callback(err, obj)
+ callback(err, obj, true);
});
}
})
View
@@ -38,7 +38,7 @@ describe('findOrCreate', function() {
})
})
})
-
+
it("returns the object if it already exists", function(done) {
Click.create({ip: '127.0.0.1'})
Click.findOrCreate({ip: '127.0.0.1'}, function(err, click) {
@@ -49,4 +49,17 @@ describe('findOrCreate', function() {
})
})
})
-})
+
+ it("should pass created as true if the object didn't exist", function(done) {
+ Click.findOrCreate({ip: '127.1.1.1'}, function(err, click, created) {
+ created.should.eql(true);
+ done();
+ })
+ })
+
+ it("should pass created as false if the object already exists", function(done) {
+ Click.findOrCreate({ip: '127.1.1.1'}, function(err, click, created) {
+ created.should.eql(false);
+ done();
+ })
+ })})

0 comments on commit 73d2cb4

Please sign in to comment.