Debug School

rakesh kumar
rakesh kumar

Posted on

How to add and remove the elements of array using push and pull in node js mongo db

findOneAndUpdate

$push

:

The $push operator is used to add an element to an array field in a MongoDB document.
It appends the specified value(s) to the array field.
If the array field doesn't exist, the operator creates it as an array with the specified value(s).
If the array field already exists and is not an array, an error will occur.
If the value being pushed is an array, it will be added as a single element to the array field.

$pull

The $pull operator is used to remove elements from an array field in a MongoDB document.
It removes all occurrences of the specified value(s) from the array field.
If the array field doesn't exist, or if it is an empty array, no changes will occur.
If the array field already exists and is not an array, an error will occur.
If the value being pulled is an array, it removes all elements that match any value in the specified array.

Certainly! Let's see how you can use the query operators $push and $pull to add and remove elements from an array field in MongoDB, using a dynamic query obtained from req.body in Node.js, and applying the MVC (Model-View-Controller) pattern.

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,
  hobbies: [String]
});

module.exports = mongoose.model('User', userSchema);
Enter fullscreen mode Exit fullscreen mode

Controller (userController.js):

const User = require('../models/user');

const UserController = {
  addHobbyToUser: async (req, res) => {
    try {
      const userId = req.body.userId; // User ID obtained from req.body
      const hobby = req.body.hobby; // Hobby to add obtained from req.body

      const filter = {
        _id: userId
      };

      const update = {
        $push: { hobbies: hobby }
      };

      const updatedUser = await User.findOneAndUpdate(filter, update, { new: true });

      res.json(updatedUser);
    } catch (error) {
      console.log('Error:', error);
      res.status(500).send('An error occurred');
    }
  },

  removeHobbyFromUser: async (req, res) => {
    try {
      const userId = req.body.userId; // User ID obtained from req.body
      const hobby = req.body.hobby; // Hobby to remove obtained from req.body

      const filter = {
        _id: userId
      };

      const update = {
        $pull: { hobbies: hobby }
      };

      const updatedUser = await User.findOneAndUpdate(filter, update, { new: true });

      res.json(updatedUser);
    } catch (error) {
      console.log('Error:', error);
      res.status(500).send('An error occurred');
    }
  }
};

module.exports = UserController;
Enter fullscreen mode Exit fullscreen mode

Route (routes.js):

const express = require('express');
const router = express.Router();

const UserController = require('../controllers/userController');

router.post('/users/:userId/add-hobby', UserController.addHobbyToUser);
router.post('/users/:userId/remove-hobby', UserController.removeHobbyFromUser);

module.exports = router;
Enter fullscreen mode Exit fullscreen mode

In this example, the User model represents a user with name and hobbies fields. The hobbies field is an array of strings.

The UserController contains two methods: addHobbyToUser and removeHobbyFromUser. The addHobbyToUser method takes the user ID from req.body.userId and the hobby to add from req.body.hobby. It constructs a filter object using the user ID and an update object using the $push operator to add the hobby to the user's hobbies array. It then uses User.findOneAndUpdate to find and update the user, returning the updated user as the response.

The removeHobbyFromUser method is similar but uses the $pull operator to remove the specified hobby from the user's hobbies array.

The route file defines two routes: one to add a hobby to a user and another to remove a hobby from a user. These routes map to the corresponding methods in the controller, using the user ID as a parameter.

To use these functionalities, you would need to make POST requests to the appropriate routes, providing the user ID and the hobby in the request body. For example

Image description

Top comments (0)