跳过或禁用mongoose模型save()调用的验证

时间:2014-11-29 05:29:21

标签: node.js mongodb validation mongoose

我正在寻找创建一个保存到MongoDB的新文档,无论它是否有效。我只是想在模型保存调用时暂时跳过mongoose验证。

在我导入CSV的情况下,CSV文件中不包含某些必填字段,尤其是其他文档的参考字段。然后,对于以下示例,不传递mongoose验证所需的检查:

var product = mongoose.model("Product", Schema({
    name: {
        type: String,
        required: true
    },
    price: {
        type: Number,
        required: true,
        default: 0
    },
    supplier: {
        type: Schema.Types.ObjectId,
        ref: "Supplier",
        required: true,
        default: {}
    }
}));

var data = {
    name: 'Test',
    price: 99
}; // this may be array of documents either

product(data).save(function(err) {
  if (err) throw err;
});

是否可以让Mongoose知道不在save()电话中执行验证?

[编辑]

我选择尝试Model.create(),但它也会调用验证过程。

6 个答案:

答案 0 :(得分:22)

支持since v4.4.2

private static String CONFIG_FILE_LOCATION = "hibernate.cfg.xml";
    private static final ThreadLocal<Session> threadLocal = new ThreadLocal<Session>();
    private  static Configuration configuration = new Configuration();
    private static org.hibernate.SessionFactory sessionFactory;
    private static String configFile = CONFIG_FILE_LOCATION;

    static {
            try {
            configuration.configure(configFile);
            sessionFactory = configuration.buildSessionFactory(); // <==here getting error
                } catch (Exception e) {                        
                        e.printStackTrace();
                }
        }

答案 1 :(得分:4)

虽然可能有一种方法可以禁用验证,但我不知道你的一个选择是使用不使用中间件的方法(因此没有验证)。其中一个是insert,它直接访问Mongo驱动程序。

Product.collection.insert({
  item: "ABC1",
  details: {
    model: "14Q3",
    manufacturer: "XYZ Company"
  },

}, function(err, doc) {
  console.log(err);
  console.log(doc);
});

答案 2 :(得分:2)

您可以拥有多个使用相同集合的模型,因此请创建第二个模型,而不使用必需的字段约束以用于CSV导入:

var rawProduct = mongoose.model("RawProduct", Schema({
    name: String,
    price: Number
}), 'products');

model的第三个参数提供了一个显式的集合名称,允许您使此模型也使用products集合。

答案 3 :(得分:2)

我可以通过替换validate方法忽略验证并保留中间件行为:

schema.method('saveWithoutValidation', function(next) {
    var defaultValidate = this.validate;
    this.validate = function(next) {next();};

    var self = this;
    this.save(function(err, doc, numberAffected) {
        self.validate = defaultValidate;
        next(err, doc, numberAffected);
    });
});

我只用mongoose 3.8.23进行了测试

答案 4 :(得分:2)

  1. 架构配置validateBeforeSave = false
  2. 使用validate methed
  3. // define
    
    var GiftSchema = new mongoose.Schema({
        name: {type: String, required: true},
        image: {type: String}
    },{validateBeforeSave:false});
    
    
    
    // use 
    var it new Gift({...});
    it.validate(function(err){
            if (err) next(err)
            else it.save(function (err, model) {
                ...
            });
        })

答案 5 :(得分:0)

根据mongoose doc

schema.set('validateBeforeSave',false);