mirror of
https://github.com/ENSL/ensl_gathers.git
synced 2025-01-19 08:01:07 +00:00
Added findorcreate method
This commit is contained in:
parent
90e6ff758a
commit
ded2d943e4
2 changed files with 39 additions and 7 deletions
|
@ -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);
|
||||
|
|
|
@ -7,14 +7,13 @@ var async = require("async");
|
|||
var userCount = 0;
|
||||
|
||||
describe("Profile model", () => {
|
||||
describe(".create", () => {
|
||||
var profile;
|
||||
|
||||
beforeEach(() => {
|
||||
profile = {
|
||||
userId: ++userCount + Math.floor(Math.random() * 10000)
|
||||
};
|
||||
});
|
||||
describe(".create", () => {
|
||||
|
||||
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();
|
||||
});
|
||||
});
|
||||
});
|
||||
});
|
||||
|
|
Loading…
Reference in a new issue