水线多对多更新现有记录
Waterline Many-To-Many update with existing records
我正在尝试编写我的模型的更新,以允许我的应用程序将 ID 数组(或对象 ID 数组)传递到服务器,并让更新函数删除所有现有关系并添加新的。
例如我发送的数据是:
{
"id":1,
"newIds":[3,4,5,6,7],
}
数据库中的当前 ID 是:
[1,2,3,4,5]
所以在更新后我希望 ID 为:
[3,4,5,6,7]
我目前的更新功能是:
var id = req.param('id'),
newIds = req.param('newIds');
User.findOne({id: id})
.exec(function(err, results){
if(err) return res.serverError(err);
var user = results;
if (user){
if (newIds && newIds.length > 0) {
user.ids.add(newIds);
}
user.save(function(err) {
if(err) {
return res.serverError(err);
};
result.success = true;
return res.json(result);
});
}
});
然而,当我调用更新时,我收到一个错误,抱怨关系已经存在(它抱怨 id 的 3,4 和 5,因为它们已经存在)。
只需将您的 add() + save()
替换为 update()
。
var id = req.param('id'),
newIds = req.param('newIds');
User.update({id: id}, {ids: newIds})
.then(function(updatedUser) {
result.success = true; // assuming you've defined result somewhere earlier
return res.json(result)
})
.catch(res.serverError)
参见:http://sailsjs.org/documentation/reference/waterline-orm/models/update
An array of primary key values passed to .update() for a collection association will set the association to contain only the records with those primary key values provided. That is- it unlinks all other records from the association.
我正在尝试编写我的模型的更新,以允许我的应用程序将 ID 数组(或对象 ID 数组)传递到服务器,并让更新函数删除所有现有关系并添加新的。
例如我发送的数据是:
{
"id":1,
"newIds":[3,4,5,6,7],
}
数据库中的当前 ID 是:
[1,2,3,4,5]
所以在更新后我希望 ID 为:
[3,4,5,6,7]
我目前的更新功能是:
var id = req.param('id'),
newIds = req.param('newIds');
User.findOne({id: id})
.exec(function(err, results){
if(err) return res.serverError(err);
var user = results;
if (user){
if (newIds && newIds.length > 0) {
user.ids.add(newIds);
}
user.save(function(err) {
if(err) {
return res.serverError(err);
};
result.success = true;
return res.json(result);
});
}
});
然而,当我调用更新时,我收到一个错误,抱怨关系已经存在(它抱怨 id 的 3,4 和 5,因为它们已经存在)。
只需将您的 add() + save()
替换为 update()
。
var id = req.param('id'),
newIds = req.param('newIds');
User.update({id: id}, {ids: newIds})
.then(function(updatedUser) {
result.success = true; // assuming you've defined result somewhere earlier
return res.json(result)
})
.catch(res.serverError)
参见:http://sailsjs.org/documentation/reference/waterline-orm/models/update
An array of primary key values passed to .update() for a collection association will set the association to contain only the records with those primary key values provided. That is- it unlinks all other records from the association.