If you have any query feel free to chat us!
Happy Coding! Happy Learning!
To create a schema for a MongoDB database using Mongoose, we need to define a schema using the mongoose.Schema()
method. This method takes an object that defines the schema's structure.
Here is an example of creating a simple schema for a User
collection with two fields name
and email
:
javascriptCopy code
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true
},
email: {
type: String,
required: true,
unique: true
}
});
module.exports = mongoose.model('User', userSchema);
In the above code, we first require the mongoose
module and then create a userSchema
using mongoose.Schema()
. Inside the schema, we define two fields, name
and email
, both of which are required. Additionally, we make the email
field unique so that there can't be any duplicate email addresses.
Finally, we export the schema as a Mongoose model using the mongoose.model()
method, passing in the name of the collection as the first argument ('User') and the schema as the second argument (userSchema
).
Once we have created the schema, we can use it to perform CRUD (Create, Read, Update, Delete) operations on the corresponding collection.
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.