如何在一个操作中在 SailsJS 中保存多条记录?
How do you save multiple records in SailsJS in one action?
我想知道在对多条记录进行更改(尤其是添加和删除)的操作中保存多条记录的最佳做法是什么。最终目标是让一个函数可以访问操作中所有已更改的数据。目前我正在嵌套保存,以便最里面的保存可以访问所有更新记录中的数据。这是我如何节省的示例:
record1.save(function (error, firstRecord) {
record2.save(function (erro, secondRecord) {
record3.save(function (err, thirdRecord) {
res.send({recordOne: firstRecord, recordTwo: secondRecord, recordThree: thirdRecord});
});
});
});
通过这种保存结构,recordOne、recordTwo、recordThree在服务器上显示的是预期的值。然而,检查 localhost/1337/modelName 发现模型没有正确更新并且数据不正确。
您可以使用内置的 promise 引擎 Bluebird 来做到这一点。
Promise.then(function() {
return [record1.save(),record2.save(),record3.save()];
}).spread(function(record1_saved,record2_saved,record3_saved){
res.send({recordOne: record1_saved, recordTwo: record2_saved, recordThree: record3_saved});
req.namespamce = this;
}).catch(function(err){
res.badRequest({
error: err.message
});
req.namespamce = this;
});
我想知道在对多条记录进行更改(尤其是添加和删除)的操作中保存多条记录的最佳做法是什么。最终目标是让一个函数可以访问操作中所有已更改的数据。目前我正在嵌套保存,以便最里面的保存可以访问所有更新记录中的数据。这是我如何节省的示例:
record1.save(function (error, firstRecord) {
record2.save(function (erro, secondRecord) {
record3.save(function (err, thirdRecord) {
res.send({recordOne: firstRecord, recordTwo: secondRecord, recordThree: thirdRecord});
});
});
});
通过这种保存结构,recordOne、recordTwo、recordThree在服务器上显示的是预期的值。然而,检查 localhost/1337/modelName 发现模型没有正确更新并且数据不正确。
您可以使用内置的 promise 引擎 Bluebird 来做到这一点。
Promise.then(function() {
return [record1.save(),record2.save(),record3.save()];
}).spread(function(record1_saved,record2_saved,record3_saved){
res.send({recordOne: record1_saved, recordTwo: record2_saved, recordThree: record3_saved});
req.namespamce = this;
}).catch(function(err){
res.badRequest({
error: err.message
});
req.namespamce = this;
});