Nodejs Schema And Model Creation Complete Guide
Understanding the Core Concepts of NodeJS Schema and Model Creation
NodeJS Schema and Model Creation: A Detailed Guide
What is Mongoose?
Mongoose is an ODM (Object Data Modeling) library for MongoDB and Node.js. It manages relationships between data, provides schema validation, and is used to translate between objects in code and the representation of those objects in MongoDB.
Installing Mongoose
Before proceeding, ensure MongoDB is installed on your system. Then, within your Node.js project, install Mongoose via npm:
npm install mongoose --save
Connecting to MongoDB
Once Mongoose is installed, you need to establish a connection to your MongoDB database:
const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost:27017/yourDatabaseName', {
useNewUrlParser: true,
useUnifiedTopology: true
}).then(() => {
console.log('Connected to MongoDB successfully');
}).catch((err) => {
console.log('Could not connect to MongoDB', err);
});
Creating a Schema
A schema defines the structure of the documents within a collection in MongoDB. In Mongoose, you define a schema using the Schema
constructor:
const Schema = mongoose.Schema;
const userSchema = new Schema({
username: {
type: String,
required: true,
unique: true
},
email: {
type: String,
required: true,
unique: true,
lowerCase: true
},
password: {
type: String,
required: true
},
age: {
type: Number,
min: [13, 'Minimum age is 13 years old'],
max: [120, 'Maximum age is 120 years old']
},
createdAt: {
type: Date,
default: Date.now
},
updatedAt: {
type: Date,
default: Date.now
}
});
- Types: Mongoose supports various data types including String, Number, Date, Boolean, etc.
- Validators: You can add validation directly within your schema definition. Common validators include
required
,unique
,min
,max
, and more. - Defaults: Set default values for certain fields, such as timestamps.
Adding Middleware to Schema
Mongoose allows you to attach pre and post hooks to your schemas. These are functions that run before or after certain events:
userSchema.pre('save', function(next) {
this.updatedAt = Date.now();
next();
});
This middleware updates the updatedAt
field every time the document is saved.
Creating a Model
With the schema defined, you can now create a model. The model is a compiled version of the schema and provides an interface to the database for creating, querying, updating, and deleting records.
const User = mongoose.model('User', userSchema);
The first argument is the singular name of the collection your model is for, while the second argument is the schema to use.
Using the Model
Once the model is created, you can start interacting with your MongoDB database:
// Create a new user
const newUser = new User({
username: 'johndoe',
email: 'johndoe@example.com',
password: 'securepassword123',
age: 28
});
newUser.save()
.then(result => console.log(result))
.catch(err => console.error(err));
// Find a user by email
User.findOne({ email: 'johndoe@example.com' })
.then(user => console.log(user))
.catch(err => console.error(err));
These are basic operations, but Mongoose supports advanced querying and aggregation capabilities as well.
Conclusion
Creating schemas and models with Mongoose in Node.js is both powerful and flexible. It ensures data consistency and simplifies your database interactions. By understanding the schema definition, middleware operations, and model usage, you can efficiently build robust database-driven applications.
Important Keywords
- Mongoose
- MongoDB
- Schema
- Model
- Validators
- Middleware
- Pre-save hook
- Queries
- Aggregation
- Node.js
- ODM (Object Data Modeling)
Online Code run
Step-by-Step Guide: How to Implement NodeJS Schema and Model Creation
Step 1: Setup Your Project
First, you need to set up a new Node.js project if you haven't done so already. Open your terminal and execute the following commands:
mkdir my-mongo-app
cd my-mongo-app
npm init -y
npm install mongoose
This will create a new directory my-mongo-app
, navigate into it, initialize a Node.js project with default settings, and then install Mongoose in your project.
Step 2: Connect to MongoDB Database
Before creating schemas and models, we need to connect to our MongoDB database. We’ll use Mongoose to simplify this process.
Create a file named app.js
and add the following code:
const mongoose = require('mongoose');
// Connection URI
const uri = 'mongodb://localhost:27017/mydatabase'; // Replace 'mydatabase' with your database name.
// Options for Mongoose connection
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(uri, options)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Connection error:', err);
});
Make sure you have MongoDB installed and running on localhost:27017
. You can also use MongoDB Atlas (a cloud-based version of MongoDB) by replacing the connection string with your own Atlas connection URI.
Step 3: Create Schema and Model
Let's create a simple schema for a User
. In Mongoose, schemas are used to define the structure of documents stored in a collection. Models are built from schemas and allow us to perform CRUD operations.
Add the following code below the connection setup in app.js
:
// Import Mongoose
const mongoose = require('mongoose');
// Define a User Schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true, // Name is a required field
trim: true, // Automatically trims whitespace
},
email: {
type: String,
required: true,
unique: true, // Email must be unique across all users
match: [/.+\@.+\..+/, 'Please fill a valid email address'], // Email validation
lowercase: true, // Converts email to lowercase before saving
trim: true,
},
age: {
type: Number,
min: 0, // Ensures age is not less than 0
max: 125, // Ensures age is not more than 125
},
createdAt: {
type: Date,
default: Date.now, // Defaults to the current timestamp when a new user is created
},
updatedAt: {
type: Date,
default: Date.now, // Defaults to the current timestamp when a user is updated
}
});
// Pre-save middleware to update the `updatedAt` timestamp
userSchema.pre('save', function(next) {
this.updatedAt = Date.now();
next();
});
// Create User model
const User = mongoose.model('User', userSchema);
// Export the User model (optional, if you want to use it elsewhere)
module.exports = User;
Step 4: Use the Model
Now that we have a User
model defined, let’s use it to create a new user in the database.
Add the following code at the end of app.js
:
async function createUser() {
try {
const user = await User.create({
name: 'Jane Doe',
email: 'janedoe@example.com',
age: 28
});
console.log('User created:', user);
} catch (err) {
console.error('Error creating user:', err.message);
} finally {
mongoose.connection.close(); // Close the connection once done
}
}
createUser(); // Call the createUser function
The above code creates a new asynchronous function createUser
that tries to create a new User
document in the MongoDB collection using the defined User
schema. If there are any validation errors or issues during the creation, they will be caught and logged. Finally, the database connection is closed.
Full Example
Here is the full app.js
file with the complete steps:
const mongoose = require('mongoose');
// Connection URI
const uri = 'mongodb://localhost:27017/mydatabase'; // Replace 'mydatabase' with your actual database name.
// Options for Mongoose connection
const options = {
useNewUrlParser: true,
useUnifiedTopology: true,
};
mongoose.connect(uri, options)
.then(() => {
console.log('Connected to MongoDB');
})
.catch((err) => {
console.error('Connection error:', err);
});
// Define a User Schema
const userSchema = new mongoose.Schema({
name: {
type: String,
required: true,
trim: true,
},
email: {
type: String,
required: true,
unique: true,
match: [/.+\@.+\..+/, 'Please fill a valid email address'],
lowercase: true,
trim: true,
},
age: {
type: Number,
min: 0,
max: 125,
},
createdAt: {
type: Date,
default: Date.now,
},
updatedAt: {
type: Date,
default: Date.now,
}
});
// Pre-save middleware to update the `updatedAt` timestamp
userSchema.pre('save', function(next) {
this.updatedAt = Date.now();
next();
});
// Create User model
const User = mongoose.model('User', userSchema);
async function createUser() {
try {
const user = await User.create({
name: 'Jane Doe',
email: 'janedoe@example.com',
age: 28
});
console.log('User created:', user);
} catch (err) {
console.error('Error creating user:', err.message);
} finally {
mongoose.connection.close(); // Close the database connection after the operation
}
}
createUser(); // Call the createUser function
Running the Application
You can now run your application using:
node app.js
If everything is set up correctly, you should see a message indicating that you’re connected to MongoDB and then the details of the created user document.
Conclusion
Top 10 Interview Questions & Answers on NodeJS Schema and Model Creation
Top 10 Questions and Answers on NodeJS Schema and Model Creation
1. What is a Schema in Node.js?
Answer: In the context of Node.js, particularly within MongoDB using Mongoose, a schema defines the structure of documents in MongoDB collections, validating data types and enforcing business logic for application fields. It specifies what data fields can exist in each document, along with the data type (e.g., string, number, date), required fields, default values, among others.
2. How do you define a Schema in Mongoose?
Answer: You define a Mongoose schema by using mongoose.Schema
. Below is a simple example:
const mongoose = require('mongoose');
const Schema = mongoose.Schema;
const userSchema = new Schema({
name: { type: String, required: true },
age: { type: Number, required: true },
email: String,
createdAt: { type: Date, default: Date.now }
});
Here, we create a userSchema
with three fields: name
, age
, email
, and createdAt
.
3. What is a Model in Node.js (using Mongoose)?
Answer: A Mongoose model is a class that is derived from a Mongoose schema. Instances of these models represent documents in MongoDB. Models provide methods to interact with the database based on that schema, such as find()
, findByIdAndUpdate()
etc.
Example:
const User = mongoose.model('User', userSchema);
4. How do you create a Model from a Schema?
Answer: Using the model()
method of the Mongoose object creates a Model. This takes two parameters - the name of the model and the schema object that it represents.
const User = mongoose.model('User', userSchema);
5. What are some common field types in a Mongoose Schema?
Answer: Common field types in a Mongoose schema include:
String
Number
Date
Buffer
Boolean
Mixed
ObjectId
Array
Each type has different validation and behavior options attached to it.
6. How do you add validation to fields in a Mongoose Schema?
Answer: Validation can be added to fields in a Mongoose schema through built-in validators or custom functions.
const userSchema = new Schema({
name: {
type: String,
required: [true, 'Name is required'],
minLength: [3, 'Name should contain at least 3 characters'],
maxLength: [40, 'Name can’t exceed 40 characters']
},
age: {
type: Number,
min: [1, 'Age must be at least 1 year old'],
max: [150, 'Age must be less than 150 years old']
}
});
7. Can Mongoose schemas have embedded objects or arrays of objects?
Answer: Yes, they can. Embedded objects and arrays of objects can be specified using nested schemas.
const addressSchema = new Schema({
street: String,
city: String,
state: String,
zip: String
});
const userSchema = new Schema({
name: String,
addresses: [addressSchema]
});
8. How do you handle relationships (e.g., one-to-many) in Mongoose schemas?
Answer: Relationships in Mongoose are generally handled through referencing other documents. For instance, a many-to-one relationship where a user can have multiple orders can be achieved like this:
const orderSchema = new Schema({
userId: { type: mongoose.Schema.Types.ObjectId, ref: 'User' },
total: Number
});
// Reference 'User' collection from 'Order' schema.
9. How do you pre- and post-save hooks work in Mongoose schemas?
Answer: Pre- and post-save hooks in Mongoose allow you to execute code before and after a document is saved to the database. They're useful for logging, sanitizing data, etc.
userSchema.pre('save', function(next) {
console.log('User is about to be saved ...');
next();
});
userSchema.post('save', function(doc, next) {
console.log('User has been saved!');
next();
});
10. What is Middleware in Mongoose schemas and how does it differ from pre/post hooks?
Answer: Middleware in Mongoose are functions that wrap around Mongoose operations. They can be defined to run before or after an operation completes. Pre and post hooks are a specific type of middleware provided by Mongoose.
Login to post a comment.