Home » Making A Schema in Mongoose

Making A Schema in Mongoose

Making A Schema in Mongoose

Introduction

Mongoose is an Object Data Modeling (ODM) 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 and it is a schema-less NoSQL document database. It means you can store JSON documents in it.

Syntax of Making a Schema In Mongoose

const mongoose = require('mongoose');
const { Schema } = mongoose;

const schemaName = new Schema({
  fieldName: {
    type: DataType,
    required: Boolean,
    unique: Boolean,
    default: DefaultValue,
    // Other validation and options
  },
  // More fields...
});
JavaScript

Why Do We Need a Schema?

  1. Structure: Schemas define the shape of your documents, ensuring consistency in your data.
  2. Validation: Schemas allow you to define validators for your data, ensuring it meets certain criteria before being saved.
  3. Middleware: Mongoose schemas support middleware functions that can execute before or after certain operations, such as saving a document.
  4. Instance Methods: Schemas allow you to define custom methods on your documents, adding more functionality to your models.
  5. Statics: You can define static methods on the schema itself, adding more capabilities at the model level.

Example

  1. Install Mongoose:
npm install mongoose
JavaScript

2. Define a Schema:

const mongoose = require('mongoose');
const { Schema } = mongoose;

const userSchema = new Schema({
  name: { type: String, required: true },
  email: { type: String, required: true, unique: true },
  password: { type: String, required: true },
  age: { type: Number, default: 18 },
  createdAt: { type: Date, default: Date.now }
});

const User = mongoose.model('User', userSchema);
JavaScript

3. Connect to MongoDB and Use the Model:

mongoose.connect('mongodb://localhost:27017/test', { useNewUrlParser: true, useUnifiedTopology: true })
  .then(() => {
    console.log('MongoDB connected!');
    
    // Create a new user
    const newUser = new User({
      name: 'John Doe',
      email: 'john.doe@example.com',
      password: 'securepassword123'
    });

    return newUser.save();
  })
  .then(user => {
    console.log('User saved:', user);
  })
  .catch(err => {
    console.error('Error:', err);
  });
JavaScript

Output

MongoDB connected!
User saved: {
  _id: ObjectId("60c72b1f9b1e8c1a8c8e4d56"),
  name: 'John Doe',
  email: 'john.doe@example.com',
  password: 'securepassword123',
  age: 18,
  createdAt: 2021-06-14T08:47:27.519Z,
  __v: 0
}
YAML

Conclusion

Mongoose schemas are a crucial part of structuring and validating your data in a MongoDB database. They offer a range of features from basic type enforcement to complex validations and middleware functions, providing a robust solution for managing your data models in a Node.js environment.

Frequently Asked Questions

1. Can you define methods in a Mongoose schema?

You can define instance methods and static functions on Mongoose models. With a little extra configuration, you can also register methods and statics in TypeScript.

2. Why do we need schema?

The purpose of a physical schema is to provide a detailed description of how data is stored in the system. It helps database developers determine which storage media should be used for each table and ensure that data is logically organized.

3. How to save data in Mongoose schema?

The save() function is generally the right way to update a document with Mongoose. With save() , you get full validation and middleware. For cases when save() isn’t flexible enough, Mongoose lets you create your own MongoDB updates with casting, middleware, and limited validation.