我发现了同样的问题https://stackoverflow.com/questions/58831178/minlength-validator-not-working-in-mongoose,但对我来说一切都很好,但验证器仍然无法工作。Note.js 文件:
const mongoose = require('mongoose')
const uniqueValidator = require('mongoose-unique-validator');
mongoose.set('strictQuery', false)
const url = process.env.MONGODB_URI
console.log('connecting to', url)
mongoose.connect(url)
.then(result => {
console.log('connected to MongoDB')
})
.catch((error) => {
console.log('error connecting to MongoDB:', error.message)
})
const noteSchema = new mongoose.Schema({
content: {
type: String,
minlength: 5,
required: true
},
important: Boolean
})
mySchema.plugin(uniqueValidator);
noteSchema.set('toJSON', {
transform: (document, returnedObject) => {
returnedObject.id = returnedObject._id.toString()
delete returnedObject._id
delete returnedObject.__v
}
})
module.exports = mongoose.model('Note', noteSchema)
app.post('/api/notes', (request, response, next) => {
const body = request.body
const note = new Note({
content: body.content,
important: body.important || false,
})
note.save()
.then(savedNote => {
response.json(savedNote)
})
.catch(error => next(error))
})
app.put('/api/notes/:id', (request, response, next) => {
const {
content,
important
} = request.body
Note.findByIdAndUpdate(
request.params.id, {
content,
important
}, {
new: true,
runValidators: true,
context: 'query'
}
)
.then(updatedNote => {
response.json(updatedNote)
})
.catch(error => next(error))
})