Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
menu search
person
Welcome To Ask or Share your Answers For Others

Categories

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

First:

var instance = new MyModel();
instance.key = 'hello';
instance.save(function (err) {
  //
});

Second

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

Is there any difference?

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
392 views
Welcome To Ask or Share your Answers For Others

1 Answer

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
assert(!instance.errors.length);

// Attributes dependent on other fields
instance.foo = (instance.bar) ? '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;
}

instance.save(function (err) {
  //
});

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
thumb_up_alt 0 like thumb_down_alt 0 dislike
Welcome to ShenZhenJia Knowledge Sharing Community for programmer and developer-Open, Learning and Share
...