はじめに
ニフクラのスクリプト機能を使っていたときに、データストアにアクセスして指定レコードの値を更新するための方法を調べました。見つけた情報を整理して残しておくことにします。
例
ここでは例として、データストア内の Friend
クラスについて、以下の処理を実行する場合を考えてみることにします。
-
objectId
の値で指定されたレコードを更新対象とする。 - 更新対象レコードの
favoriteFood
フィールドに新しい値を設定する。 - 更新対象レコードの
objectId
と、favoriteFood
に新たに設定する値は、スクリプトの呼び出し元からリクエストメッセージボディにて指定されるものとする。
最初に考えた実装
最初に考えた方法は、 equalTo()
や fetch()
を使って対象レコードを明示的にフェッチして、得られたレコードに対して更新処理をおこなうというものでした。
updateFriend.js
module.exports = async function (req, res) {
// APIキーの指定
const applicationKey = 'APPLICATION_KEY';
const clientKey = 'CLIENT_KEY';
const NCMB = require('ncmb');
const ncmb = new NCMB(applicationKey, clientKey);
// パラメータチェック
const friendId = req.body.friendId;
const food = req.body.food;
if (friendId == undefined || food == undefined) {
// パラメータ未設定時はエラー
res.status(400).json({
"hint": "friendId, foodを設定してください。",
"message": "友達情報の更新に失敗しました。"
});
return;
}
const Friend = ncmb.DataStore('Friend');
try {
const friend = await Friend
.equalTo('objectId', friendId)
.fetch()
.set('favoriteFood', food)
.update();
res.status(200).json(friend);
} catch (error) {
res.status(500).json(error);
}
}
より効率的な実装
上の実装でも目的は果たせるのですが、次のコードのようにして、 new Friend
で得られたオブジェクトに指定 objectId
を設定した上で更新対象のフィールドに新しい値を設定すると、余計なフェッチ処理をおこなわずにすみます。
updateFriend.js
module.exports = async function (req, res) {
// APIキーの指定
const applicationKey = 'APPLICATION_KEY';
const clientKey = 'CLIENT_KEY';
const NCMB = require('ncmb');
const ncmb = new NCMB(applicationKey, clientKey);
// パラメータチェック
const friendId = req.body.friendId;
const food = req.body.food;
if (friendId == undefined || food == undefined) {
// パラメータ未設定時はエラー
res.status(400).json({
"hint": "friendId, foodを設定してください。",
"message": "友達情報の更新に失敗しました。"
});
return;
}
const Friend = ncmb.DataStore('Friend');
try {
const friend = await (new Friend)
.set('objectId', friendId)
.set('favoriteFood', food)
.update();
res.status(200).json(friend);
} catch (error) {
res.status(500).json(error);
}
}