Last active
September 14, 2020 22:09
-
-
Save luandevpro/85a196442ad51f85509058ec289c0646 to your computer and use it in GitHub Desktop.
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
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) |
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
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