Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Skip or Disable validation for mongoose model save() call

I'm looking to create a new Document that is saved to the MongoDB regardless of if it is valid. I just want to temporarily skip mongoose validation upon the model save call.

In my case of CSV import, some required fields are not included in the CSV file, especially the reference fields to the other document. Then, the mongoose validation required check is not passed for the following example:

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;
});

Is it possible to let Mongoose know to not execute validation in the save() call?

[Edit]

I alternatively tried Model.create(), but it invokes the validation process too.

like image 718
Sithu Avatar asked Nov 29 '14 05:11

Sithu


People also ask

What does save () do in Mongoose?

Mongoose | save() Function The save() function is used to save the document to the database. Using this function, new documents can be added to the database.

What is the need of Mongoose .how it is useful for validation?

Mongoose gives us a set of useful built-in validation rules such: Required validator checks if a property is not empty. Numbers have min and max validators. Strings have enum , match , minlength , and maxlength validators.

Does update call save in Mongoose?

When you create an instance of a Mongoose model using new , calling save() makes Mongoose insert a new document. If you load an existing document from the database and modify it, save() updates the existing document instead.

Is Mongoose validation customizable?

Validation is an important part of the mongoose schema. Along with built-in validators, mongoose also provides the option of creating custom validations.


2 Answers

This is supported since v4.4.2:

doc.save({ validateBeforeSave: false });
like image 178
Tamlyn Avatar answered Nov 08 '22 08:11

Tamlyn


Though there may be a way to disable validation that I am not aware of one of your options is to use methods that do not use middleware (and hence no validation). One of these is insert which accesses the Mongo driver directly.

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

}, function(err, doc) {
  console.log(err);
  console.log(doc);
});
like image 26
cyberwombat Avatar answered Nov 08 '22 08:11

cyberwombat