首页 > 解决方案 > Node.js Update Form for CRUD APP

问题描述

The form updates but only updates the first entry in my database. It does not update the entry of the specified id.

This is my schema:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/myDB');
var dbSchema = mongoose.Schema({
objID : String,
productName : String,
price : String,
quantity: Number
});
var Document = mongoose.model('Document', dbSchema);

The app.post Document.update is not creating the document on the specified id. When the information is posted through my form, the update takes place on the first db entry.

app.get('/update', function(req, res,) {
res.render('update', { title: 'Express' });
});

app.post('/updated/',
function(req, res) {
        Document.update({
            objID : req.body.id_name,
            productName : req.body.product_name,
            price : req.body.price_name,
            quantity: req.body.quantity_name
        }, function(err, obj) {
            if (!err) {
                res.redirect('/update');}
            else {
                res.send(err)
            }
        });
    });

I have also tried these two methods.

app.post('/updated',
function(req, res) {
    Document.findOneAndUpdate({objID: req.params.objID}, req.body, {new: true},
        (err, obj) => {
            if (!err) {
                res.redirect('/update');
            }
            else {
                res.send(err)
            }
        });
});


app.post('/updated/',
function (req,res) {
    Document.findByIdAndUpdate(req.params.objID, {$set: req.body}, function (err, product) {
        if (err) return next(err);
        res.send('Product udpated.');
    });
});

If anyone can just give the last nudge to assist me i would truly appreciate it.

And this is my update.pug file.

doctype html
head
meta(charset='utf-8')
meta(name='viewport' content='width=device-width, initial-scale=1.0')
title Superb Grocery IS
link(rel='stylesheet' type="text/css" href='stylesheets/style.css')
script(type='text/javascript' src='javascripts/validate.js')
.main-nav
ul.nav
    li.name Superb Grocery IS
    li
        a(href='index') Home
    li
        a(href='listing') Listing
    li
        a(href='entry') Add
    li
        a(href='update') Update
    li
        a(href='delete') Delete
header
#wrapperr
    h1(align='center' style='color:blueviolet') Update Products
    form(name='form3' action='/updated' method='post' style='margin-top: 
20px')
        input(name='_method', value='PUT', type='hidden')
        table#table2(align='center' border='3')
            tr
                td
                    label(for='entry_id') ID:
                td
                    input#entry_id(type='text' name='id_name' pattern='^[a-zA-Z][a-zA-Z0-9-_\.]{5}$' placeholder='RWS35O' onblur='alphanumeric(this)' required='')
            tr
                td
                    label(for='entry_product') Product:
                td
                    input#entry_product(type='text' name='product_name' onblur='letpattern(this)' required='')
            tr
                td
                    label(for='entry_price') Price:
                td
                    input#entry_price(type='text' name='price_name' placeholder='9999 OR 9999.99' onblur='price(this)' required='')
            tr
                td
                    label(for='entry_quantity') Quantity:
                td
                    input#entry_quantity(type='text' name='quantity_name' placeholder='9999' pattern='[0-9]' onblur='numeric(this)' required='')
            tr
                td(colspan='2' align='center')
                    button.reset(type='reset' value='Reset') Reset
                    button.update_btn(type='submit' value='Submit') Update

标签: javascriptnode.jsmongodbmongoose

解决方案


const User = require('../models/user')
const jwt = require('../helpers/jwt')

module.exports = class {
  static register(req, res, next) {
    let user = {
      name: req.body.name,
      email: req.body.email,
      password: req.body.password
    }
    User.create(user)
      .then(result => {
        res.status(201).json(result)
      })
      .catch(err => {
        next(err)
      })
  }

  static login(req, res, next) {
    let user = {
      email: req.body.email,
      password: req.body.password
    }
    // console.log(user);

    User.findOne(user)
      .then(userLogin => {
        let token = jwt.generateToken({
          email: userLogin.email,
          id: userLogin._id
        })
        res.status(200).json({ token: token })
      })
      .catch(err => {
        ;(err.statusCode = 400), (err.message = 'Email or Password is invalid')
        next(err)
      })
  }

  static getUser(req, res, next) {
    try {
      let user = {
        _id: req.body.user._id,
        name: req.body.user.name,
        email: req.body.user.email,
        imageUrl: req.body.user.imageUrl,
        role: req.body.user.role,
        balance: req.body.user.balance
      }
      res.status(200).json(user)
    } catch (err) {
      next(err)
    }
  }

  static logout(req, res, next) {
    res.status(200).json({
      message: 'Successfully logout',
      accountType: req.body.user.accountType
    })
  }
}

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

// router.get('/', )
router.use('/users', require('./users'))
router.use('/products', require('./product'))
router.use('/transactions', require('./transaction'))

module.exports = router



==== router user ====

const express = require('express')
const router = express.Router()
const User = require('../controllers/userController')
const auth = require('../middlewares/auth')

/* GET users listing. */
router.post('/register', User.register)
router.post('/login', User.login)
router.get('/', auth.authentication, User.getUser)
router.post('/logout', auth.authentication, User.logout)
module.exports = router


===env===
jwt_key, port, db_uri


推荐阅读