Last active
August 20, 2019 04:34
-
-
Save WangHansen/c022f876f3c3034667fdfa161a28fbef to your computer and use it in GitHub Desktop.
Mongoose with Javascript for user table
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import mongoose from "mongoose" | |
// Schema | |
const UserSchema = mongoose.Schema({ | |
firstName: { | |
type: String, | |
required: true | |
}, | |
lastName: String, | |
username: { | |
type: String, | |
unique: true, | |
required: true, | |
lowercase: true | |
}, | |
password: { | |
type: String, | |
required: true | |
}, | |
company: { | |
type: Schema.Types.ObjectId, | |
ref: "Company", | |
required: true | |
}, | |
gender: { | |
type: Number, | |
enum: [0, 1], | |
default: 0, | |
required: true | |
}, | |
friends: [{ | |
type: String, | |
}], | |
creditCards: { | |
type: Map, | |
of: string | |
} | |
}) | |
// Virtuals | |
UserSchema.virtual("fullName").get(function() { | |
return this.firstName + this.lastName | |
}) | |
// Methods | |
UserSchema.methods.getGender = function() { | |
return this.gender > 0 "Male" : "Female" | |
} | |
// Static methods | |
UserSchema.statics.findWithCompany = function(id) { | |
return this.findById(id).populate("company").exec() | |
} | |
// Document middlewares | |
UserSchema.pre("save", function(next) { | |
if (this.isModified("password")) { | |
this.password = hashPassword(this.password) | |
} | |
}); | |
// Query middlewares | |
UserSchema.post("findOneAndUpdate", async function(doc) { | |
await updateCompanyReference(doc); | |
}); | |
export default model("User", UserSchema) |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment