如何解决猫鼬模型验证不适用于模型更新
我已经成功创建了Mongoose模型并为其属性添加了验证。例如,属性不能为空或必须唯一。当我创建新文档时,模型及其验证将按预期工作。但是问题是,
当我尝试更新文档时,验证不起作用,它接受空白或重复值,无法理解这里出了什么问题。
我的模特
/**
* Module dependencies.
*/
const mongoose = require('mongoose');
const crypto = require('crypto');
const Schema = mongoose.Schema;
/**
* User Schema
*/
const ProductSchema = new Schema({
brandName: { type: String,default: '',index: true },unit: { type: String,default: '' }
});
/**
* Validations
*/
ProductSchema.path('brandName').validate(function (brandName) {
if (this.skipValidation()) return true;
return brandName.length;
},'Brand Name cannot be blank');
ProductSchema.path('brandName').validate(function (brandName) {
return new Promise(resolve => {
const Product = mongoose.model('Product');
if (this.skipValidation()) return resolve(true);
// Check only when it is a new brandName or when brandName field is modified
if (this.isNew || this.isModified('brandName')) {
Product.find({ brandName }).exec((err,products) => resolve(!err && !products.length));
} else resolve(true);
});
},'Product Name `{VALUE}` already exists');
ProductSchema.path('unit').validate(function (unit) {
if (this.skipValidation()) return true;
return unit.length;
},'Unit cannot be blank');
/**
* Methods
*/
ProductSchema.methods = {
skipValidation: function () {
return false;
}
};
ProductSchema.pre('findOneAndUpdate',function(next) {
this.options.runValidators = true;
next();
});
const ProductModel = mongoose.model("Product",ProductSchema);
module.exports = ProductModel;
我正在尝试为ProductName实施它,但是无法正常工作。
我已经为findOneAndUpdate添加了预钩,但是现在我遇到了错误
reason: TypeError: this.skipValidation is not a function
at C:\1-projects\om\ProductManager\Model\productModel.js:53:12
版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。