Skip to content

Instantly share code, notes, and snippets.

@luandevpro

luandevpro/Post.js

Last active Sep 14, 2020
Embed
What would you like to do?
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