猫鼬:即使通过{new:true}

时间:2019-12-19 19:05:37

标签: mongodb mongoose

POST和DELETE请求正在工作,但即使在通过{new: true}后也未按照其他答案建议的那样PUT无法工作。 我检查了文档中的猫鼬,没有找到任何可能解决此问题的方法。

终端日志为:PUT /api/persons/5dfbb8677d7d960358dbdead 404 175 - 2.273 ms -

请求正文未记录,仅记录了“-”。 POST并非如此。

相关代码:

app.post('/api/persons', (request, response) => {
  const body = request.body

  const person = new Person({
    name: body.name,
    number: body.number,
  })

  person
  .save()
  .then(savedContact => {
    response.json(savedContact.toJSON())
  })
})

app.put('api/persons/:id', (request, response, next) => {
  const body = request.body
  const person = {
    name: body.name,
    number: body.number,
  }

  person
  .findByIdAndUpdate(request.params.id, person, { new: true })
  .then(updatedContact => {
      response.json(updatedContact.toJSON())
    })
  .catch(error => next(error))
})

app.delete('/api/persons/:id', (request, response, next) => {
  Person
  .findByIdAndRemove(request.params.id)
  .then(result => {
    response.status(204).end()
  })
  .catch(error => {next(error)})

const errorHandler = (error, request, response, next) => {

  if (error.name === 'CastError' && error.kind == 'ObjectId') {
    return response.status(400).send({ error: 'malformatted id' })
  }

  next(error)
}

app.use(errorHandler)
})

完整文件:

require('dotenv').config()
const express = require('express')
const app = express()
app.use(express.static('build'))

const bodyParser = require('body-parser')
app.use(bodyParser.json())

const cors = require('cors')
app.use(cors())

const morgan = require('morgan')

morgan.token('req_body', function(req, res) {
  if (req.method === 'POST' || req.method === 'PUT'){
    return JSON.stringify(req.body);
  }
});

morgan.token('req_key', function(req, res) {
  if (req.method === 'GET' || req.method === 'PUT'){
    return JSON.stringify(req.params.id);
  }
});

app.use(morgan(':method :url :status :res[content-length] - :response-time ms :req_body :req_key'))

const Person = require('./models/person')

app.get('/api/persons', (request, response) => {
  Person.find({}).then(persons => {
    response.json(persons.map(person => person.toJSON()))
  })
})

app.get('/api/persons/:id', (request, response) => {
  Person
  .findById(request.params.id)
  .then(person => {
    response.json(person.toJSON())
  })
  .catch(error => {
    console.log(error)
    response.status(404).end()
  })
})

app.post('/api/persons', (request, response) => {
  const body = request.body

  const person = new Person({
    name: body.name,
    number: body.number,
  })

  person
  .save()
  .then(savedContact => {
    response.json(savedContact.toJSON())
  })
})

app.put('api/persons/:id', (request, response, next) => {
  const body = request.body
  const person = {
    name: body.name,
    number: body.number,
  }

  Person
  .findByIdAndUpdate(request.params.id, person, { new: true })
  .then(updatedContact => {
      response.json(updatedContact.toJSON())
    })
  .catch(error => next(error))
})

app.delete('/api/persons/:id', (request, response, next) => {
  Person
  .findByIdAndRemove(request.params.id)
  .then(result => {
    response.status(204).end()
  })
  .catch(error => {next(error)})
})

const errorHandler = (error, request, response, next) => {

  if (error.name === 'CastError' && error.kind == 'ObjectId') {
    return response.status(400).send({ error: 'malformatted id' })
  }

  next(error)
}

app.use(errorHandler)


const PORT = process.env.PORT
app.listen(PORT, ()=>{console.log(`Server running on ${PORT}`)})

1 个答案:

答案 0 :(得分:0)

您的人对象是错误的,因此不更新记录。

app.put('/api/persons/:id', (request, response, next) => {
  const body = request.body
  const person = {
    name: body.name,
    number: body.number,
  }

  Person
  .findByIdAndUpdate(request.params.id, person, { new: true })
  .then(updatedContact => {
      response.json(updatedContact.toJSON())
    })
  .catch(error => next(error))
})