Nodejs /猫鼬哪种方法更适合创建文档?

【字号: 日期:2024-04-16浏览:18作者:雯心
(adsbygoogle = window.adsbygoogle || []).push({}); 如何解决Nodejs /猫鼬哪种方法更适合创建文档??

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

因此,作为您可以做的一些事情的基本示例:

var instance = new MyModel();// Validatingassert(!instance.errors.length);// Attributes dependent on other fieldsinstance.foo = (instance.bar) ? ’bar’ : ’foo’;// Create missing associationsAuthorModel.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中创建新文档的方法。

首先

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

第二

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

有什么区别吗?

相关文章: