Erik Erik - 2 months ago 8x
Node.js Question

Nodejs/mongoose. which approach is preferable to create a document?

I've found two approach to create new document in nodejs when I work with mongoose.


var instance = new MyModel();
instance.key = 'hello'; (err) {


MyModel.create({key: 'hello'}, function (err) {

Is there any difference?


Yes, the main difference is the ability to do computations before you save or as a reaction to information that comes up while you're building your new model. The most common example would be making sure the model is valid before trying to save it. Some other examples might be creating any missing relations before saving, values that need to be calculated on the fly based on other attributes, and models that need to exist but could potentially never be saved to the database (aborted transactions).

So as a basic example of some of the things you could do:

var instance = new MyModel();

// Validating

// Attributes dependent on other fields = ( ? 'bar' : 'foo';

// Create missing associations
AuthorModel.find({ name: 'Johnny McAwesome' }, function (err, docs) {
  if (!docs.length) {
     // ... Create the missing object

// Ditch the model on abort without hitting the database.
if(abort) {
  delete instance;
} (err) {