【问题标题】:ReactJS + Axios + NodeJS - _id: Cannot read property 'ownerDocument' of nullReactJS + Axios + NodeJS - _id:无法读取 null 的属性“ownerDocument”
【发布时间】:2020-06-12 19:55:32
【问题描述】:

我有这个通过 Axios 连接到 Node.js 后端的 ReactJS 应用程序。我正在尝试更新,并且有效负载是正确的,但我有一个尴尬的问题:它说我没有发送需要更新的 _id。这是我的 mongoose Schema,Axios 中的请求和它的 express 后端方法。

axios 请求:

    submit () {
    let data = this.state.category
    axios({
        method: this.state.category._id ? 'put':'post',
        url: `/category/${this.state.category._id || ''}`,
        data: data
    })
    .then(res => {
        let list = this.state.categoryList
        list.push(res.data.category)
        this.update({
            alert: {
                type: "success",
                text: "Category updated"
            },
            categoryList: list
        })
      this.toggleLarge()
    })
    .catch(e => {
        this.update({
            category: {
                errors: e.errors
            },
            alert: {
                type: "danger",
                text: "Error",
                details: e
            }
        })
    })
}

Mongoose 架构:

const mongoose = require('mongoose');
const uniqueValidator = require('mongoose-unique-validator');

let Schema = mongoose.Schema;

let categorySchema = new Schema({
    description: {
        type: String,
        unique: true,
        required: [true, 'Category required']
    }
});

categorySchema.methods.toJSON = function() {

    let category = this;
    let categoryObject = category.toObject();

    return categoryObject;
}

categorySchema.plugin(uniqueValidator, { message: '{PATH} must be unique' });

module.exports = mongoose.model('Category', categorySchema);

表达方式:

 app.put('/category/:id', [verifyToken], (req, res) => {
    let id = req.params.id;

    Category.findByIdAndUpdate(id, req.body, { new: true, runValidators: true }, (err, categoryDB) => {
        if (err) {
            return res.status(400).json({
                ok: false,
                err
            });
        }
        res.json({
            ok: true,
            category: categoryDB
        });

    })
});

请求负载:

{"description":"Saladitos","errors":{},"_id":"5e5940dd7c567e1891c32cda","__v":0}

然后回应:

"Validation failed: _id: Cannot read property 'ownerDocument' of null, description: Cannot read property 'ownerDocument' of null"

【问题讨论】:

    标签: node.js reactjs mongodb express axios


    【解决方案1】:

    你不必说{id: id} 只是传递上下文等于这样的查询

               {runValidators: true, context: 'query'}
    

    【讨论】:

      【解决方案2】:

      我可以看到您可能不会将 ObjectId:_id 更改为其他名称。但是对于已经这样做并看到类似问题的人,请检查此。 https://liuzhenglai.com/post/5dbd385f8dea5b6b578765d9

      所以你可能需要把你的代码改成这个

      const id = request.params.id
      Model.findByIdAndUpdate(
              id, 
              {id:id ,description: req.body.description, ... }, 
              {runValidators: true, context: 'query'},
              callback
      )
      

      【讨论】:

        【解决方案3】:

        这是findByIdAndUpdate的合约:

        A.findByIdAndUpdate(id, update, options, callback)
        

        您的更新对象是 req.body,其中包含 _id。我猜它也会尝试更新_id,这不应该发生。

        尝试指定要更新的列

         Model.findByIdAndUpdate(id, { description: req.body.description, ... }, options, callback)
        

        希望这会有所帮助。

        【讨论】:

        • 像魅力一样工作!非常感谢@vujadin
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 2020-08-08
        • 2018-10-04
        • 2021-12-31
        • 2023-03-08
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多