0
0
NodejsHow-ToBeginner · 4 min read

How to Use Mongoose in Node.js: Simple Guide with Examples

To use mongoose in Node.js, first install it with npm install mongoose. Then, import it, connect to your MongoDB database using mongoose.connect(), define a schema with mongoose.Schema, create a model, and use that model to interact with your database.
📐

Syntax

Here is the basic syntax to use mongoose in Node.js:

  • Import mongoose: Load the library to use it.
  • Connect: Use mongoose.connect() with your MongoDB URL.
  • Define Schema: Create a schema to describe your data structure.
  • Create Model: Make a model from the schema to work with documents.
  • Use Model: Perform actions like create, read, update, and delete.
javascript
import mongoose from 'mongoose';

// Connect to MongoDB
mongoose.connect('mongodb://localhost:27017/mydatabase', {
  useNewUrlParser: true,
  useUnifiedTopology: true
});

// Define a schema
const MySchema = new mongoose.Schema({
  name: String,
  age: Number
});

// Create a model
const MyModel = mongoose.model('MyModel', MySchema);

// Use the model
// Example: create a new document
const doc = new MyModel({ name: 'Alice', age: 25 });
doc.save();
💻

Example

This example shows how to connect to MongoDB, define a schema and model, create a new document, and then find all documents in the collection.

javascript
import mongoose from 'mongoose';

async function run() {
  try {
    // Connect to MongoDB
    await mongoose.connect('mongodb://localhost:27017/testdb', {
      useNewUrlParser: true,
      useUnifiedTopology: true
    });

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

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

    // Create and save a new user
    const user = new User({ name: 'Bob', age: 30 });
    await user.save();

    // Find all users
    const users = await User.find();
    console.log(users);

    // Close connection
    await mongoose.connection.close();
  } catch (error) {
    console.error('Error:', error);
  }
}

run();
Output
[ { _id: <ObjectId>, name: 'Bob', age: 30, __v: 0 } ]
⚠️

Common Pitfalls

Some common mistakes when using mongoose include:

  • Not waiting for the connection to open before performing database operations.
  • Forgetting to handle asynchronous operations with async/await or promises.
  • Defining schemas or models incorrectly, such as missing required fields or wrong types.
  • Not closing the database connection after operations, which can cause hanging processes.

Always handle errors and use try/catch blocks with async functions.

javascript
/* Wrong: Not waiting for connection and missing async */
import mongoose from 'mongoose';
mongoose.connect('mongodb://localhost:27017/testdb');

const User = mongoose.model('User', new mongoose.Schema({ name: String }));

const user = new User({ name: 'Eve' });
user.save(); // This may fail if connection is not ready

/* Right: Using async/await and waiting for connection */
async function run() {
  await mongoose.connect('mongodb://localhost:27017/testdb');
  const User = mongoose.model('User', new mongoose.Schema({ name: String }));
  const user = new User({ name: 'Eve' });
  await user.save();
  await mongoose.connection.close();
}
run();
📊

Quick Reference

Here is a quick summary of key mongoose methods and concepts:

ConceptDescription
mongoose.connect(url, options)Connects to MongoDB database.
new mongoose.Schema({})Defines the structure of documents.
mongoose.model(name, schema)Creates a model to interact with a collection.
Model.find()Finds documents matching criteria.
Model.findById(id)Finds a document by its ID.
new Model(data).save()Creates and saves a new document.
Model.updateOne(filter, update)Updates a single document.
Model.deleteOne(filter)Deletes a single document.

Key Takeaways

Always connect to MongoDB with mongoose.connect before database operations.
Define schemas to describe your data structure clearly.
Use async/await to handle mongoose operations safely.
Create models from schemas to perform CRUD actions.
Close the connection when done to avoid hanging processes.