Update model with Mongoose, Express, NodeJS

后端 未结 5 2136
一向
一向 2020-12-23 22:15

I\'m trying to update an instantiated model (\'Place\' - I know it works from other routes) in a MongoDB and have spent a while trying to properly do so. I\'m also trying t

5条回答
  •  春和景丽
    2020-12-23 22:37

    you could do something similar based on the illustration below

    Updated:

    In My solution: I have created a model, controller and route to depict the similar scenario (interacting with MongoDB method like updating/creating data to the database) in Nodejs MVC framework with MongoDB as the database

    // user.js - this is the user model
    
    const mongoose = require('mongoose')
    const validator = require('validator')
    
    const User = mongoose.model('User', {
      name: {
        type:  String,
        required:  true,
        trim:  true
      },
      email: {
        type:  String,
        required:  true,
        trim:  true,
        lowercase:  true,
        validate(value) {
          if (!validator.isEmail(value)) {
            throw  new  Error('Email is invalid')
          }
        }
      },
      password: {
        type:  String, 
        required:  true, 
        minlength:  7, 
        trim:  true,
        validate(value) {
          if (value.toLowerCase().includes('password')) { 
            throw  new  Error('Password cannot contain "password"') 
          } 
        } 
      },
      age: { 
        type:  Number, 
        default:  0, 
        validate(value) { 
          if (value  <  0) { 
            throw  new  Error('Age must be a positive number') 
          }
        }
      }
    });   
    
    module.exports  =  User
    
    // userController.js**
    
    exports.updateUser = async(req, res) => {
      const updates = Object.keys(req.body)
      const allowedUpdates = ['name', 'email', 'password', 'age']
      const isValidOperation = updates.every((update) => { 
        allowedUpdates.includes(update))
        if (!isValidOperation) {
          return res.status(400).send('Invalid updates!')
        }
        try {
          const user = await UserModel.findByIdAndUpdate(req.params.id, 
            req.body, { new: true, runValidators: true })
          if (!user) {
            return res.status(404).send({ message: 'You do not seem to be registered' })
          }
          res.status(201).send(user)
        } catch (error) {
          res.status(400).send(error)
        }
    }
    
    // **router.js**
    router.patch('/user/:id', userController.updateUser)
    

    I hope this would help anyone, you can also Read more.

提交回复
热议问题