'how do I validate an update method in mongoose schema?
I am trying to validate my update method using mongoose custom validators but my validation fails regardless of the data I send in.
Schema:
const TodoSchema = new mongoose.Schema({
title: {
type: String,
validate: {
validator: async function(title){
const user = await this.constructor.findOne({title})
if(user){
if(this.id === user.id){
return true
} return false
} return true
},
message: props => `"${props.value}" already exists`
},
required: [true, "Title cannot be empty"]
},
description: {
type: String,
}
})
update Controller:
async function editItemPagePost(request, response){
try {
await TodoModel.findOneAndUpdate(
{_id: request.params.id},
{_id: request.params.id, title: request.body.title, description: request.body.description},
{ runValidators: true, context: 'query' }
)
response.redirect("/")
} catch (error) {
response.send(error)
}
}
error:
{
"errors": {
"title": {
"name": "ValidatorError",
"message": "this.constructor.findOne is not a function",
"properties": {
"message": "this.constructor.findOne is not a function",
"type": "user defined",
"path": "title",
"value": "item 2",
"reason": {}
},
"kind": "user defined",
"path": "title",
"value": "item 2",
"reason": {}
}
},
"_message": "Validation failed",
"name": "ValidationError",
"message": "Validation failed: title: this.constructor.findOne is not a function"
}
I've tried using the pre-hook validator to automatically validate, but it didn't work either.
Does anyone know why it doesn't work?
Solution 1:[1]
Apparently, the "this" keyword works differently within the update method documentation. So I ended up changing my code as follows.
const TodoSchema = new mongoose.Schema({
title: {
type: String,
validate: {
validator: async function(title) {
const model = await TodoModel.findOne({title})
if(model){
if(this.id === model.id){
return true
} return false
} return true
},
message: props => `"${props.value}" already exists`
},
required: [true, "Title cannot be empty"]
},
description: {
type: String,
}
})
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Derick Damoah |
