Nodejs/猫鼬.哪种方法更适合创建文档? [英] Nodejs/mongoose. which approach is preferable to create a document?

查看:52
本文介绍了Nodejs/猫鼬.哪种方法更适合创建文档?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

当我使用猫鼬时,我发现了两种在nodejs中创建新文档的方法.

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

第一:

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

第二

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

有什么区别吗?

推荐答案

是的,主要区别在于保存之前可以进行计算的能力,或者是对构建新模型时出现的信息的反应.最常见的示例是在尝试保存模型之前确保模型有效.其他一些示例可能是在保存之前创建任何丢失的关系,需要基于其他属性即时计算的值以及需要存在但可能永远不会保存到数据库(异常交易)的模型.

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

这篇关于Nodejs/猫鼬.哪种方法更适合创建文档?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆