前提
- 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);
});
});
コレが一番単純な方法だと思いますが、他によい方法があればコメント頂けるとうれしいです。