Adding Comments to the DB

Dear Sciaku Learner you are not logged in or not enrolled in this course.

Please Click on login or enroll now button.

If you have any query feel free to chat us!

Happy Coding! Happy Learning!

Lecture 323:- Adding Comments to the DB

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.

37. Database Relations (Posts, Comments)

Comments: 2

profile
@niteshguptav63
17-Nov-2024, 01:39 PM

I am not able to access videos from second class and further. I have already completed first class

profile
@niteshguptav63
16-Nov-2024, 10:56 AM

When will I get my course?

profile
@admin79
17-Nov-2024, 01:29 PM

Now, Your query was resolved.

Frequently Asked Questions (FAQs)

How do I register on Sciaku.com?
How can I enroll in a course on Sciaku.com?
Are there free courses available on Sciaku.com?
How do I purchase a paid course on Sciaku.com?
What payment methods are accepted on Sciaku.com?
How will I access the course content after purchasing a course?
How long do I have access to a purchased course on Sciaku.com?
How do I contact the admin for assistance or support?
Can I get a refund for a course I've purchased?
How does the admin grant access to a course after payment?