Skip to content

Instantly share code, notes, and snippets.

@luandevpro
Last active September 14, 2020 22:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save luandevpro/85a196442ad51f85509058ec289c0646 to your computer and use it in GitHub Desktop.
Save luandevpro/85a196442ad51f85509058ec289c0646 to your computer and use it in GitHub Desktop.
const mongoose = requier("mongoose")
const { ObjectId } = mongoose.Schema
const postSchema = new mongoose.Schema({
text: String,
image: String,
likes: [{type: ObjectId, ref: "user"}],
comments: [
{
text: String,
createAt: {type: Date,default: Date.now},
postedBy: {type: ObjectId, ref: "user"}
}
],
postedBy: {type: ObjectId,ref: "user"},
createAt: {
type: Date,
default: Date.now
}
})
const autoPopulatePostedBy = function(next){
this.populate("postedBy" , "_id name avatar");
this.populate("comments.postedBy" , "_id name avatar");
next();
}
postSchema
.pre("findOne" , autoPopulatePostedBy)
.pre("find" , autoPopulatePostedBy)
postSchema.index({ postedBy: 1, createdAt: 1 });
module.exports = mongoose.model("post",postSchema)
const mongoose = requier("mongoose")
const { ObjectId } = mongoose.Schema
const userSchema = new mongoose.Schema({
email: String,
name: String,
avatar: {
type: String,
default: "/static/images/profile-image.png"
},
about: String,
following: [{type: ObjectId,ref: "user"}],
followers: [{type: ObjectId,ref: "user"}],
},
// auto createAt vs updateAt field
{timestamps: true}
)
const autoPopulateFollowingAndFollowers = function(next){
this.populate("following" , "_id name user");
this.populate("followers" , "_id name user");
next();
}
userSchema.pre("findOne" , autoPopulateFollowingAndFollowers)
module.exports = mongoose.model("user", userSchema)
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment