From ded2d943e4f805c4f4b0b1f9b6812207419c4e6c Mon Sep 17 00:00:00 2001 From: Chris Blanchard Date: Fri, 28 Aug 2015 14:19:46 +0100 Subject: [PATCH] Added findorcreate method --- db/models/profile.js | 13 +++++++++++++ spec/profile.js | 33 ++++++++++++++++++++++++++------- 2 files changed, 39 insertions(+), 7 deletions(-) diff --git a/db/models/profile.js b/db/models/profile.js index c6b0a56..a1bb92e 100644 --- a/db/models/profile.js +++ b/db/models/profile.js @@ -18,4 +18,17 @@ var profileSchema = new Schema({ profileSchema.path('userId').index({ unique: true }); +profileSchema.static("findOrCreate", (user, callback) => { + if (!user || typeof user.id !== 'number') return callback(new Error("Invalid user")); + let self = this; + self.findOne({userId: user.id}, (error, profile) => { + if (error) return callback(error); + if (profile) return callback(null, profile); + self.create({userId: user.id}, (error, result) => { + if (error) return callback(error); + return callback(null, result); + }); + }); +}); + module.exports = mongoose.model("Profile", profileSchema); diff --git a/spec/profile.js b/spec/profile.js index 1c642c2..34425b6 100644 --- a/spec/profile.js +++ b/spec/profile.js @@ -7,14 +7,13 @@ var async = require("async"); var userCount = 0; describe("Profile model", () => { + var profile; + beforeEach(() => { + profile = { + userId: ++userCount + Math.floor(Math.random() * 10000) + }; + }); describe(".create", () => { - var profile; - - beforeEach(() => { - profile = { - userId: ++userCount + Math.floor(Math.random() * 10000) - }; - }); it ("creates a new profile", done => { Profile.create(profile, (error, result) => { @@ -52,4 +51,24 @@ describe("Profile model", () => { }); }); }); + describe(".findOrCreate", () => { + it ("returns a profile if user exists", done => { + Profile.create(profile, (error, result) => { + if (error) return done(error); + assert.equal(result.userId, profile.userId); + Profile.findOrCreate({id: profile.userId}, (error, foundProfile) => { + if (error) return done(error); + assert.equal(foundProfile._id.toString(), result._id.toString()); + done(); + }); + }); + }); + it ("creates a profile if user does not exist", done => { + Profile.findOrCreate({id: profile.userId}, (error, foundProfile) => { + if (error) return done(error); + assert.equal(profile.userId, foundProfile.userId); + done(); + }); + }); + }); });