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

Categories

0 votes
382 views
in Technique[技术] by (71.8m points)

node.js - 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.

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

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

1 Answer

0 votes
by (71.8m points)

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

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...