I am building a MERN stack project, this project have a feature social media. Like social media nowdays, you have a post, profile, and comment in the post. I tried to implementing populate for my data in the backend but its not working. What did i do wrong in the code, can someone please explain it to me.
it return empty array
My 3 model :
const CommentSchema = new mongoose.Schema({
ContentMessage : {
type : String
},
PostID : {
type : String
},
WriterID : {
type : String
},
user : {
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedprofiles"
},
post : {
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedposts"
}
}, {timestamps : true});
const CommentModel = mongoose.model("comments", CommentSchema);
module.exports = CommentModel;
const SosmedPostSchema = new mongoose.Schema({
Username : {
type : String
},
Content : {
type : String
},
Documents : {
type : String
},
user : {
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedprofiles"
},
comments : [{
type: mongoose.Schema.Types.ObjectId,
ref: "comments"
}]
}, {timestamps : true});
const SosmedPostModel = mongoose.model("sosmedposts", SosmedPostSchema);
module.exports = SosmedPostModel;
const SosmedProfileSchema = new mongoose.Schema({
Username : {
type : String
},
FullName : {
type : String
},
ProfilePicture : {
type : String
},
Bio : {
type : String
},
Post : [{
type : mongoose.Schema.Types.ObjectId,
ref : "sosmedposts"
}]
}, {timestamps : true});
const SosmedProfileModel = mongoose.model("sosmedprofiles", SosmedProfileSchema);
module.exports = SosmedProfileModel
Post Route/Controller :
const getPostById = (req, res) => {
const Id = req.params.id;
SosmedPostModel.findOne({_id : Id})
.populate({
path : "user",
populate : {
path : "comments"
}
})
.then(posts => {
res.json(posts);
})
}
router.get("/socialmedia/post/:id", getPostById);