Creating a Schema in MongoDB
What is a Schema ?
Schema does not need to have the same set of fields or structure, and common fields in a collection’s documents. If you are familiar with sql queries, you might know that we define the variables and data types in a predefined structure when creating tables.But when using schema you can consider the following points.
- Design your schema according to user requirements.
- Combine objects into one document if you will use them together. Otherwise separate them (but make sure there should not be need of joins).
- Duplicate the data (but limited) because disk space is cheap as compare to compute time.
- Do joins while write, not on read.
- Optimize your schema for most frequent use cases.
- Do complex aggregation in the schema.
Lets try out how to create a schema to get a better idea.
First create a directory in your project folder to store these separately. Now create file to create the schema.Here we should require Mongoose. Go through the article to get a better idea on mongoose and to install it if you haven't .
var mongoose = require('mongoose');
Now load the schema which is in mongoose.
var Schema = mongoose.Schema;
Now build the schema.
var userSchema = new Schema({
//Defining the data fields and datatypes });
var userSchema = new Schema({
Name : {type:String,required:true},
Email : {type:String,required:true},
Password : {type:String,required:true}
});
The permitted Schema Types are,
- String
- Number
- Date
- Buffer
- Boolean
- Mixed
- ObjectId
- Array
Now this should be exported as we are using an external file.So that this schema can be used easily.
module.exports = mongoose.model("User",userSchema);
//userschema is the schema that we created
So the data will be passed to the database through the schema that we created.
Here we cannot define any data beyond the schema we created and feed them.
To feed data to the database we have to design the front end.
Hope to see you soon with how to design a front end add data to the database.
Comments
Post a Comment