Added findorcreate method

This commit is contained in:
Chris Blanchard 2015-08-28 14:19:46 +01:00
parent 90e6ff758a
commit ded2d943e4
2 changed files with 39 additions and 7 deletions

View file

@ -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);

View file

@ -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();
});
});
});
});