TypeError:无法读取未定义的属性“ isPrivate”

时间:2020-03-18 01:30:35

标签: node.js mongodb mongoose

我正在尝试更新使用猫鼬的findByIdAndUpdate方法创建的模型。但是,我不断收到这样的错误消息:我要更改的属性的模型未定义。下面是代码。

这是我的草图架构

//create new schema
const Schema = mongoose.Schema;
//sketch schema with 2 fields
const sketchSchema = new Schema({
    name: { type: String, default: 'sketch.js' },
    isPrivate: {type: Boolean, default: true }
}, {
    timestamps: true, //this means it automatically let you know when it was created and modified
})

//create a model from the user schema def to use it
const Sketch = mongoose.model('Sketch', sketchSchema);

module.exports = Sketch;

我的API代码

router.route("/sketches/:id").put((req, res) => {

  //find sketch by id and ONLY update privacy field

  Sketch.findByIdAndUpdate(req.params.id, 
      {
       $set: {isPrivate: req.body.isPrivate}
  },{
      new: true
  })
  .then(sketch => {
      sketch.save()
      .then(() => res.json(sketch))
  })
  .catch(err => res.status(400).json('Error: ' + err))
})

这是我的服务器应用代码

//create instances of express and CORS
const express = require('express');
const cors = require('cors');
const mongoose = require('mongoose');

//this
require('dotenv').config()

//create server app
const app = express();
//what is this line saying
const port = process.env.PORT || 5000;


const sketchRouter = require('./routes');
app.use('/exercises', sketchRouter);

//Middleware 
app.use(cors());
app.use(express.json());

//mongoDB database set up
const uri  = process.env.ATLAS_URI;
mongoose.connect(uri, {useNewUrlParser: true, useCreateIndex: true}) 
const connection = mongoose.connection;
connection.once('open', () => {
    console.log("MongoDB DB est. successfully")
})


//Start the server
app.listen(port, () => { 
    console.log(`Server is running on port: ${port}`);
});


我正在使用邮递员通过其对象ID测试针对特定草图的放置请求,并传递请求的主体以将草图的IsPrivate字段从true更改为false

此处使用邮递员的要求身体图片

postman put request image

2 个答案:

答案 0 :(得分:0)

您的req.body未定义。您是否尝试过检查值或reqreq.body?没有更多的数据,我不能说为什么它是未定义的...但是它是。

答案 1 :(得分:0)

我终于弄清楚了为什么收到未定义的错误消息。这是由于我对代码的排序错误:特别是,配置了要在应用程序的主要中间件之前使用的路由文件。本质上,所有API函数都未启用JSON。