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

Sit*_*thu 11 validation mongoose mongodb node.js

我正在寻找创建一个保存到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;
});
Run Code Online (Sandbox Code Playgroud)

是否有可能让Mongoose知道不在save()呼叫中执行验证?

[编辑]

我或者尝试过Model.create(),但它也会调用验证过程.

Tam*_*lyn 27

自v4.4.2起支持此功能:

doc.save({ validateBeforeSave: false });
Run Code Online (Sandbox Code Playgroud)


cyb*_*bat 6

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

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

}, function(err, doc) {
  console.log(err);
  console.log(doc);
});
Run Code Online (Sandbox Code Playgroud)