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)

2 Comments

@niteshguptav63
niteshguptav63 Nov 17, 2024 at 1:39 PM

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

@niteshguptav63
niteshguptav63 Nov 16, 2024 at 10:56 AM

When will I get my course?

@admin79
admin79 Nov 17, 2024 at 1:29 PM

Now, Your query was resolved.

Frequently Asked Questions About Sciaku Courses & Services

Quick answers to common questions about our courses, quizzes, and learning platform

Didn't find what you're looking for?

help_center Contact Support