Sails.js模型 - 插入或更新记录 [英] Sails.js model - insert or update records
问题描述
一直在试用Sails.js,我正在编写一个从第三方API导入数据并保存到MySQL表中的应用程序。基本上我正在尝试将数据同步到我的应用程序以进行进一步分析,更新我的记录或根据需要创建新记录。
Been trying out Sails.js and I'm writing an app that imports data from a third-party API and saves in into a MySQL table. Basically I'm trying to sync data over to my app for further analysis, updating my records or creating new records as needed.
我查看了Sails的API和我看到了查找,创建和更新记录的方法,但没有根据情况插入/更新记录的内置方法。我是否忽略了某些内容,或者我是否需要自己实现?
I've looked through Sails' API and I see methods to find, create and update records but no built-in method to insert/update records based on the situation. Did I overlook something, or will I need to implement this myself?
如果我必须自己实现这一点,是否有人知道插入/更新的良好设计模式?
If I have to implement this myself, does anyone know of a good design pattern for insert/update?
这就是我认为的样子......
This is what I think it might look like…
_.each(importedRecords, function(record){
MyModel.find({id: record.id}).exec(function findCB(err, found){
if(found.length){
MyModel.update(record.id, task).exec(function(err, updated){
if(err) { //returns if an error has occured, ie id doesn't exist.
console.log(err);
} else {
console.log('Updated MyModel record '+updated[0].name);
}
});
}else{
MyModel.create(record).exec(function(err, created){
if(err) { //returns if an error has occured, ie invoice_id doesn't exist.
console.log(err);
} else {
console.log('Created client record '+created.name);
}
});
}
});
});
我是朝着正确的方向前进,还是有更优雅的解决方案?
Am I headed in the right direction, or is there a more elegant solution?
另外,我在这个应用程序中处理了很多不同的模型,这意味着要在我的每个模型中重新创建这个代码块。有没有办法可以扩展基础Model对象,为所有模型添加此功能。
Also, I'm dealing with a lot of different models in this app, which would mean recreating this block of code across each of my models. Is there a way I can extend the base Model object to add this functionality for all models.
谢谢,
John
Thanks, John
推荐答案
我已经改写了重要的Mash代码,因此代码更少,更通用。
现在,您可以像调用findOrCreate一样调用updateOrCreate。它看起来像这样:
I have rewritten Critical Mash code, so its way less code, and more generic. Now you can call updateOrCreate the same way you call findOrCreate. And it looks like that:
module.exports.models = {
updateOrCreate: function(criteria, values){
var self = this; // reference for use by callbacks
// If no values were specified, use criteria
if (!values) values = criteria.where ? criteria.where : criteria;
return this.findOne(criteria).then(function (result){
if(result){
return self.update(criteria, values);
}else{
return self.create(values);
}
});
}
};
这样你就可以用同样的方式编写标准。无需处理密钥,代码更简单。
So that way you can write criteria the same way. no need to work on the key, and the code is so much simpler.
这篇关于Sails.js模型 - 插入或更新记录的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!