skip to Main Content

this question about backend development node.js how do i update a database data by using object id
please help me to learn those things custom validator

app.patch("/users/:id", async (req, res) => {
  

  try {
    const user = await User.findByIdAndUpdate(req.params.id, req.body, {
      runValidators: true,
      new: true,
    });
    if (!user) {
      return res.status(404).send();
    }
    res.send(user);
  } catch (e) {
    res.status(400).send()
  }
});

this my code please modify to add validators like allowedUpdates …

2

Answers


  1. You can use mongoose ObjectId validator:

    mongoose.Types.ObjectId.isValid(id)
    

    Update your code to look like this:

    // require mongoose or import it
    const mongoose = require('mongoose')
    
    app.patch("/users/:id", async (req, res) => {
       if (mongoose.Types.ObjectId.isValid(req.params.id)) {
          await User.findByIdAndUpdate(req.params.id, req.body, 
             (error, docs) => {
                if (error) {
                   // return "error" response
                   return res.status(500).json({
                      status: 500,
                      message: error
                   })
                } else {
                   // return "success" response
                   return res.status(200).json({
                      status: 200,
                      message: 'user successfully updated',
                      data: docs
                   })
                }
             })
       } else {
          // return "bad request" response
          return res.status(400).json({
             status: 400,
             message: 'bad request'
          })
       }
    })
    
    Login or Signup to reply.
  2. You can try like this :

    app.patch("/users/:id", async (req, res) => {
      const allowedUpdates = [ // Define the fields you want to allow for update];
    
      const updates = Object.keys(req.body);
      const isValidOperation = updates.every((update) =>
        allowedUpdates.includes(update)
      );
    
      if (!isValidOperation) {
        return res.status(400).send({ error: 'Invalid updates!' });
      }
    
      try {
        const user = await User.findByIdAndUpdate(req.params.id, req.body, {
          runValidators: true,
          new: true,
        });
    
        if (!user) {
          return res.status(404).send();
        }
    
        res.send(user);
      } catch (e) {
        res.status(400).send();
      }
    });
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search