$in
In schema
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
age: Number,
city: String
});
module.exports = mongoose.model('User', userSchema);
Controller (userController.js):
const User = require('../models/user');
const UserController = {
getUsersByAges: async (req, res) => {
try {
const ages = [20, 25, 30]; // Array of ages to search for
const users = await User.find({ age: { $in: ages } });
res.render('users', { users });
} catch (error) {
console.log('Error:', error);
res.status(500).send('An error occurred');
}
}
};
module.exports = UserController;
Route (routes.js):
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/userController');
router.get('/users', UserController.getUsersByAges);
module.exports = router;
View (users.ejs or users.hbs):
<h1>Users</h1>
<ul>
<% users.forEach(user => { %>
<li><%= user.name %> (Age: <%= user.age %>) - <%= user.city %></li>
<% }); %>
</ul>
In this example, we have a User model defined using Mongoose, representing a user with name, age, and city fields.
The UserController contains a method getUsersByAges that demonstrates the usage of the $in operator. It retrieves users whose ages match any value in the ages array. The method calls User.find({ age: { $in: ages } }) to perform the query.
In the route file, we define a route to handle the request for users. It maps the getUsersByAges method in the controller to the corresponding route.
The view file displays the retrieved users' information in a list format using a loop (forEach in this case). The user's name, age, and city are rendered for each user.
This example demonstrates how the $in operator can be used in the context of MVC in Node.js and MongoDB. The controller handles the logic, the model represents the data structure, the route maps the request to the appropriate controller method, and the view displays the retrieved users' information.
Another example
Model (user.js):
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
city: String,
hobbies: [String]
});
module.exports = mongoose.model('User', userSchema);
Controller (userController.js):
const User = require('../models/user');
const UserController = {
getUsersByHobbies: async (req, res) => {
try {
const hobbies = req.body.hobbies; // Hobbies obtained from req.body
const filter = {
hobbies: { $in: hobbies }
};
const users = await User.find(filter);
res.json(users);
} catch (error) {
console.log('Error:', error);
res.status(500).send('An error occurred');
}
}
};
module.exports = UserController;
Route (routes.js):
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/userController');
router.get('/users', UserController.getUsersByHobbies);
module.exports = router;
In this example, the User model represents a user with name, city, and hobbies fields. The hobbies field is an array of strings.
The UserController contains a method named getUsersByHobbies, which takes the hobbies from req.body.hobbies. It constructs a filter object using the $in operator to match users whose hobbies are present in the specified hobbies array. It then uses User.find to retrieve users that have at least one of the specified hobbies.
The route file defines a route that handles the GET request to retrieve users by hobbies. It maps the getUsersByHobbies method in the controller to the corresponding route.
To use this functionality, you would need to make a GET request to the /users route, sending the hobbies in the request body. For example, using axios in a client-side JavaScript code:
axios.get('/users', {
params: {
hobbies: ['Reading', 'Cooking'] // Hobbies to match
}
})
.then(response => {
const users = response.data;
// Handle the retrieved users
})
.catch(error => {
// Handle the error
});
query operator $ Nin
Model (user.js):
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
age: Number,
city: String
});
module.exports = mongoose.model('User', userSchema);
Controller (userController.js):
const User = require('../models/user');
const UserController = {
getUsersExcludingAges: async (req, res) => {
try {
const excludedAges = [20, 25, 30]; // Array of ages to exclude
const users = await User.find({ age: { $nin: excludedAges } });
res.render('users', { users });
} catch (error) {
console.log('Error:', error);
res.status(500).send('An error occurred');
}
}
};
module.exports = UserController;
Route (routes.js):
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/userController');
router.get('/users', UserController.getUsersExcludingAges);
module.exports = router;
View (users.ejs or users.hbs):
<h1>Users</h1>
<ul>
<% users.forEach(user => { %>
<li><%= user.name %> (Age: <%= user.age %>) - <%= user.city %></li>
<% }); %>
</ul>
In this example, the User model represents a user with name, age, and city fields.
The UserController contains a method named getUsersExcludingAges, which demonstrates the usage of the $nin operator. It retrieves users whose ages do not match any value in the excludedAges array. The method uses User.find({ age: { $nin: excludedAges } }) to perform the query.
Another Example
Assuming you have a basic MVC structure with the following components:
Model (user.js):
const mongoose = require('mongoose');
const userSchema = new mongoose.Schema({
name: String,
city: String,
hobbies: [String]
});
module.exports = mongoose.model('User', userSchema);
Controller (userController.js):
const User = require('../models/user');
const UserController = {
getUsersByHobbies: async (req, res) => {
try {
const excludedHobbies = req.body.excludedHobbies; // Hobbies to exclude obtained from req.body
const filter = {
hobbies: { $nin: excludedHobbies }
};
const users = await User.find(filter);
res.json(users);
} catch (error) {
console.log('Error:', error);
res.status(500).send('An error occurred');
}
}
};
module.exports = UserController;
Route (routes.js):
const express = require('express');
const router = express.Router();
const UserController = require('../controllers/userController');
router.get('/users', UserController.getUsersByHobbies);
module.exports = router;
In this example, the User model represents a user with name, city, and hobbies fields. The hobbies field is an array of strings.
The UserController contains a method named getUsersByHobbies, which takes the excluded hobbies from req.body.excludedHobbies. It constructs a filter object using the $nin operator to exclude users with hobbies that are present in the excluded hobbies array. It then uses User.find to retrieve users that do not have any of the excluded hobbies.
The route file defines a route that handles the GET request to retrieve users by hobbies. It maps the getUsersByHobbies method in the controller to the corresponding route.
To use this functionality, you would need to make a GET request to the /users route, sending the excluded hobbies in the request body. For example, using axios in a client-side JavaScript code:
axios.get('/users', {
params: {
excludedHobbies: ['Reading', 'Cooking'] // Hobbies to exclude
}
})
.then(response => {
const users = response.data;
// Handle the retrieved users
})
.catch(error => {
// Handle the error
});
Top comments (0)