Creating Schema for Comments

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 322:- Creating Schema for Comments

To create a schema for comments in MongoDB, we can use MongooseJS, a Node.js library that provides a straightforward way to define schemas for our data models. Here's an example schema for comments:

phpCopy code

const mongoose = require('mongoose'); const commentSchema = new mongoose.Schema({  text: {    type: String,    required: true,  },  author: {    id: {      type: mongoose.Schema.Types.ObjectId,      ref: 'User',    },    username: String,  },  created: {    type: Date,    default: Date.now,  }, }); module.exports = mongoose.model('Comment', commentSchema);

This schema defines a Comment model with three fields: text, author, and created. The text field is a required string that contains the text of the comment. The author field is an object with two properties: id and username. The id property is a reference to the User model, which we'll define later, and the username property is a string that contains the username of the comment author. The created field is a date that contains the time when the comment was created.

We can create a new comment by creating a new instance of the Comment model and calling the save() method:

javascriptCopy code

const Comment = require('./comment'); const newComment = new Comment({  text: 'This is a new comment',  author: {    id: 'user_id',    username: 'user_name',  }, }); newComment.save((err, comment) => {  if (err) {    console.error(err);  } else {    console.log('New comment created:', comment);  } });

This will save the new comment to the database and log the newly created comment object to the console. We can then fetch the comments from the database and display them on our web page.

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?