If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To add comments to the database, we need to create a schema for comments, similar to how we created a schema for users and posts.
Here is an example schema for comments:
javascriptCopy code
const mongoose = require("mongoose");
const commentSchema = new mongoose.Schema(
{
text: {
type: String,
required: true,
},
author: {
type: mongoose.Schema.Types.ObjectId,
ref: "User",
required: true,
},
post: {
type: mongoose.Schema.Types.ObjectId,
ref: "Post",
required: true,
},
},
{ timestamps: true }
);
const Comment = mongoose.model("Comment", commentSchema);
module.exports = Comment;
In this schema, we define the text of the comment, the author of the comment (which is a reference to the User schema), and the post that the comment belongs to (which is a reference to the Post schema).
We also include a timestamp so that we can keep track of when the comment was created and updated.
After creating the schema, we can save comments to the database using Mongoose's create
method, like so:
javascriptCopy code
const comment = new Comment({
text: "This is a comment.",
author: userId, // the ID of the user who wrote the comment
post: postId, // the ID of the post that the comment belongs to
});
comment.save((err) => {
if (err) {
console.error(err);
} else {
console.log("Comment saved successfully!");
}
});
Note that in this example, userId
and postId
are the IDs of the user who wrote the comment and the post that the comment belongs to, respectively.
Comments: 2
I am not able to access videos from second class and further. I have already completed first class
When will I get my course?
Now, Your query was resolved.