当我使用mongoose时,我发现了两种在nodejs中创建新文档的方法.
第一:
var instance = new MyModel();
instance.key = 'hello';
instance.save(function (err) {
//
});
Run Code Online (Sandbox Code Playgroud)
第二
MyModel.create({key: 'hello'}, function (err) {
//
});
Run Code Online (Sandbox Code Playgroud)
有什么区别吗?
Swi*_*ift 44
是的,主要区别在于您在保存之前进行计算的能力,或者在您构建新模型时对信息的反应.最常见的示例是在尝试保存模型之前确保模型有效.其他一些示例可能是在保存之前创建任何缺失的关系,需要根据其他属性动态计算的值,以及需要存在但可能永远不会保存到数据库的模型(中止的事务).
所以作为你可以做的一些事情的基本例子:
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) {
//
});
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
20379 次 |
| 最近记录: |