LoginSignup
0
2

More than 5 years have passed since last update.

Mongooseでクエリパラメータの数を動的に変更する

Posted at

前提

  • Express
  • Mongoose
  • APIっぽいものを作っている

単純な例

次のようなクエリで、findに渡すパラメータをオプショナルとしたい場合
※スキーマ定義などは省略

sample.js
router.get('/', function(req, res, next) {
  let userId = req.query.userid;
  let userType = req.query.usertype || null;

  User.find({userid: userId, usertype: userType}, (err, docs) => {
    // userTypeをオプショナルなパラメータとしたい !!
    res.json(docs);
  });

});

事前にクエリを作成しておくとよい

sample2.js
router.get('/', function(req, res, next) {
  let userId = req.query.userid;
  let userType = req.query.usertype || null;
  }

  // findの第一引数に渡すqueryオブジェクトを事前に作成
  let query = {
    userid: userId,
  }
  // 必要に応じて追加
  if (userType != null) {
    query.type = dripType;
  }

  User.find(query, (err, docs) => {
    res.json(docs);
  });

});

コレが一番単純な方法だと思いますが、他によい方法があればコメント頂けるとうれしいです。

0
2
1

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
2