0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?

More than 5 years have passed since last update.

ニフクラのスクリプト機能でデータストアにアクセスして指定レコードの値を更新する

Last updated at Posted at 2019-10-18

はじめに

ニフクラのスクリプト機能を使っていたときに、データストアにアクセスして指定レコードの値を更新するための方法を調べました。見つけた情報を整理して残しておくことにします。

ここでは例として、データストア内の 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);
  }
}

参考情報

0
0
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
0
0

Delete article

Deleted articles cannot be recovered.

Draft of this article would be also deleted.

Are you sure you want to delete this article?