【发布时间】:2021-02-01 17:13:55
【问题描述】:
我有一个带有put 请求的快速应用程序,如果我发现此电话簿中已存在此人的姓名,则更新电话簿(我正在使用具有unique: true 的“mongoose-unique-validator”验证中的选项)
但只有当我将findByIdAndUpdate 的runValidators 设置为true 时,我才会遇到此put 请求的问题
这是我的代码
架构
const personSchema = new mongoose.Schema({
name: { type: String, required: true, minlength: 3, unique: true },
number: {
type: String,
required: true,
validate: {
validator: function (str) {
//the function to validate the number
},
message: "phone number must contain at least 8 digits",
},
},
});
personSchema.plugin(uniqueValidator);
personSchema.set("toJSON", {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString();
delete returnedObject._id;
delete returnedObject.__v;
},
});
const Person = mongoose.model("Person", personSchema);
put 请求
app.put("/api/persons/:id", (req, res, next) => {
const id = req.params.id;
console.log(id);
const body = req.body;
const person = {
name: body.name,
number: body.number,
};
// opts is supposed to be true; and this is where i have the problem
const opts = { runValidators: false };
Person.findByIdAndUpdate(id, person, opts)
.then((updatedPerson) => {
res.json(updatedPerson);
})
.catch((error) => next(error));
});
错误处理程序
const errorHandler = (error, req, res, next) => {
console.error(error.message);
if (error.name === "CastError" && error.kind == "ObjectId") {
return res.status(400).send({ error: "malformatted id" });
} else if (error.name === "ValidationError") {
return res.status(400).json({ error: error.message });
}
next(error);
};
app.use(errorHandler);
我得到的错误是
error: "Validation failed: name: Cannot read property 'ownerDocument' of null"
【问题讨论】:
标签: node.js mongodb express validation mongoose