简体   繁体   中英

Postman PUT method not updating data

Put method actually responds with 200 OK but data in db is not updating, i am using mongoDB. Here is product.js file:

router.put('/products/:id', async (req, res) => {
    try {
        let product = await Product.findOneAndUpdate({_id: req.params.id}, {
            $set: {
                title: req.body.title,
                price: req.body.price
            }
        }, {upsert: true})
        
        res.json({
            success: true,
            updatedProduct: product
        })
    } catch(err) {
        res.status(500).json({
            success: false,
            message: err.message
        })
    }
})

Here is the image from postman, response is 200OK, but when i refresh and check mongoDB, data is still the same. https://i.stack.imgur.com/asUoV.png

This is code from server.js file.

const express = require('express')
const morgan = require('morgan')
const bodyParser = require('body-parser')
const mongoose = require('mongoose')
const dotenv = require('dotenv')

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

// env file
dotenv.config()

const app = express()

// connect mongoDB
mongoose.connect(process.env.DATABASE, (err) => {
    if(err) {
        console.log(err)
    } else {
        console.log('connected to database')
    }
})

// middleware
app.use(morgan('dev'))
app.use(bodyParser.json())
app.use(bodyParser.urlencoded({ extended: false }))

// require apis
const productRoutes = require('./routes/product')
const categorytRoutes = require('./routes/category')
const ownerRoutes = require('./routes/owner')

app.use('/api', productRoutes)
app.use('/api', categorytRoutes)
app.use('/api', ownerRoutes)

// Initial response
app.get('/', function(req, res, next) {
    res.send("Hello world");
})

app.listen(8080, (err) => {
    if(err) {
        console.log(err)
    }
})
router.put('/products/:id', async (req, res) => {
  try {
    const updatedProduct = await Product.updateOne({ _id: req.params.id},
    { $set: { title: req.body.title,price: req.body.price });
    res.status(200).send("updated successfully");} 
    catch (err) {
    res.status(400).json({ message: err.message });
  }
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM