Skip to main content

Compiling Your First Model in Mongoose

Compiling Your First Model in Mongoose | Rustcode

Compiling Your First Model in Mongoose

In Mongoose, a model is a compiled representation of a schema. Models act as constructors for documents and provide an interface to interact with the corresponding MongoDB collections.


Defining a Schema

Before compiling a model, you need to define a schema that maps to the structure of documents in your MongoDB collection. The schema defines fields, data types, validations, and other constraints.

const mongoose = require('mongoose');

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

Compiling the Model

Use the mongoose.model() function to compile your schema into a model. The first argument is the string name of the model (and implicitly the MongoDB collection name, pluralized), and the second is the schema.

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

The model name 'User' corresponds to the 'users' collection in MongoDB by default.


Using the Model

Once compiled, you can use the model to create, read, update, and delete documents.

// Creating a new user document
const newUser = new User({
  name: { first: 'John', last: 'Doe' },
  email: 'john.doe@example.com',
  age: 30
});

newUser.save()
  .then(doc => console.log('User saved:', doc))
  .catch(err => console.error('Error saving user:', err));
  

Summary Table

Step Description Code Example
Define Schema Map document structure and validations new mongoose.Schema({ ... })
Compile Model Create model constructor from schema mongoose.model('Name', schema)
Use Model Create and query MongoDB documents new Model() and save()

Best Practices

  • Define clear and consistent schemas.
  • Use schema validations to keep data integrity.
  • Compile models once per schema and reuse them.
  • Use meaningful model names aligned with collection content.

Conclusion

Compiling your first model in Mongoose is the foundational step to interacting with MongoDB collections in a structured and efficient way. Clear schemas and well-defined models enable reliable data management in your applications.

Comments