Mongoose Tutorial

Mongoose is a software library for Node.js that makes it easier to work with MongoDB. In simple terms, it helps programmers interact with and manage data in MongoDB by providing a structured way to define data models, create, read, update, and delete documents, and perform other operations

Setting Up Mongoose

To get started Install Mongoose and require it in your Node.js application.

const mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/mydatabase', { useNewUrlParser: true, useUnifiedTopology: true });

Defining a Schema

Schemas define the structure of your documents in MongoDB.


const Schema = mongoose.Schema;
const userSchema = new Schema({
  name: String,
  age: Number,
}); 

Creating a Mode

Models are constructors compiled from the Schema definitions.

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

Creating Documents

You can create new documents using the model constructor.

const newUser = new User({ name: 'John', age: 30 });
newUser.save((err) => {
  if (err) throw err;
  console.log('User saved successfully');
});

Querying Documents

Mongoose provides methods to query the database. For example, finding all users with a specific age.

User.find({ age: 30 }, (err, users) => {
  if (err) throw err;
  console.log(users);
}); 

Updating Documents

You can update documents using Mongoose.

User.updateOne({ name: 'John' }, { age: 31 }, (err) => {
  if (err) throw err;
  console.log('User updated');
});

Deleting Documents

You can also delete documents using Mongoose.

User.deleteOne({ name: 'John' }, (err) => {
  if (err) throw err;
  console.log('User deleted');
});  

Middleware

Mongoose allows you to define middleware functions that run before or after specific actions, such as saving a document.

userSchema.pre('save', function(next) {
  // Do something before saving
  next();
});

Validation

Mongoose supports validation for schema fields.

const userSchema = new Schema({
  name: {
    type: String,
    required: true,
  },
  age: {
    type: Number,
    min: 18,
  },
});

Populating References

When dealing with relationships between documents, Mongoose allows you to populate referenced documents.

const postSchema = new Schema({
  title: String,
  author: {
    type: Schema.Types.ObjectId,
    ref: 'User',
  },
});

Post.find({}).populate('author').exec((err, posts) => {
  if (err) throw err;
  console.log(posts);
});