gpt4 book ai didi

node.js - ReactJS + Axios + NodeJS - _id : Cannot read property 'ownerDocument' of null

转载 作者:太空宇宙 更新时间:2023-11-03 23:47:44 24 4
gpt4 key购买 nike

我有一个通过 Axios 连接到 Node 后端的 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"

最佳答案

这是findByIdAndUpdate的契约:

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

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

尝试指定要更新的列

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

希望这有帮助。

关于node.js - ReactJS + Axios + NodeJS - _id : Cannot read property 'ownerDocument' of null,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60456338/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com