Skip to content

HTTPS clone URL

Subversion checkout URL

You can clone with
or
.
Download ZIP
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...
commit 73d2cb4045f8a9c2536c96275c6174deecfcded7 1 parent 29812a2
@drudge authored
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
6 README.md
@@ -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
8 index.js
@@ -23,10 +23,12 @@ 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) {
@@ -34,7 +36,7 @@ function findOrCreatePlugin(schema, options) {
}
var obj = new self(conditions)
obj.save(function(err) {
- callback(err, obj)
+ callback(err, obj, true);
});
}
})
View
17 test/index_test.js
@@ -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();
+ })
+ })})
Please sign in to comment.
Something went wrong with that request. Please try again.