Lesson 5
Advanced Query Techniques with Mongoose
Advanced Query Techniques with Mongoose

In this lesson, we'll learn how to retrieve and manipulate data more efficiently in a MongoDB database using Mongoose. By the end of this lesson, you'll be able to use powerful query methods to get exactly the data you need.

What You'll Learn

In this lesson you'll learn:

  • Setting up Mongoose and Express
  • Defining a schema and model for advanced queries
  • Creating routes with advanced queries to get specific data
Step 1: Setting up Mongoose and Express

Let's set up our basic Express application and connect it to a MongoDB database using Mongoose. This is important because it lays the foundation for retrieving and manipulating data.

JavaScript
1const express = require('express'); 2const mongoose = require('mongoose'); 3 4const app = express(); 5const PORT = 3000; 6 7// Set mongoose strictQuery to true to suppress deprecation warning 8mongoose.set('strictQuery', true); 9 10// Connect to MongoDB 11mongoose.connect('mongodb://127.0.0.1:27017/todo-app', { 12 useNewUrlParser: true, 13 useUnifiedTopology: true 14}).then(() => { 15 console.log('Connected to MongoDB'); 16}).catch((error) => { 17 console.error('Connection error', error); 18 process.exit(1); 19}); 20 21app.use(express.json());

In this code chunk, we import the necessary modules (express and mongoose). We set up the Express application and specify the port for the server. We then configure Mongoose to connect to a MongoDB database named todo-app. If the connection is successful, a confirmation message is logged; otherwise, an error is printed, and the process exits.

Step 2: Defining a Schema and Model for ToDo Items

Now we'll define a schema and model for ToDo items, which will help us organize and interact with our data more effectively.

JavaScript
1// Define a schema and model for ToDo items 2const todoSchema = new mongoose.Schema({ 3 task: { type: String, required: true }, 4 completed: { type: Boolean, default: false } 5}); 6 7const Todo = mongoose.model('Todo', todoSchema);

In this code chunk, we define a schema using Mongoose. The schema includes fields for task (a required string) and completed (a boolean with a default value of false). We then create a model called Todo based on this schema, which provides an interface to interact with our ToDo items in the database.

Step 3: Creating a Route with an Advanced Query

Let's create a route that uses an advanced query to find all incomplete ToDo items. This is helpful for retrieving specific subsets of data from our database.

JavaScript
1// Route with advanced query to find all incomplete todos 2app.get('/todos/incomplete', async (req, res) => { 3 try { 4 const incompleteTodos = await Todo.find({ completed: false }); 5 res.json(incompleteTodos); 6 } catch (error) { 7 res.status(500).json({ message: 'Failed to load incomplete todos' }); 8 } 9});

In this code chunk, we define a GET route at /todos/incomplete. Within this route, we perform an advanced query using the find method to retrieve all ToDo items where completed is false. The results are sent back as a JSON response. If there's an error during this process, a 500 status code and error message are returned.

Step 4: Starting the Server

Finally, let's start the server to listen for incoming requests. This allows us to interact with our API endpoints.

JavaScript
1app.listen(PORT, () => { 2 console.log(`Server running on http://localhost:${PORT}`); 3});

In this code chunk, we start the Express server on the specified port (3000). A message is logged to the console to indicate that the server is running and ready to accept requests.

Conclusion

In this lesson, we set up an Express application with Mongoose, defined a schema and model for ToDo items, created a route with an advanced query, and started the server. By mastering these techniques, you can efficiently retrieve and manipulate data in a MongoDB database using Mongoose.

Enjoy this lesson? Now it's time to practice with Cosmo!
Practice is how you turn knowledge into actual skills.