LoginSignup
0

More than 5 years have passed since last update.

Sails.js(0.10.x)のModel.native()でIDを指定したクエリーを書く方法

Posted at

Sails.js(0.10.x)のModel.native()でIDを指定したクエリーを書く方法

MongoDB on Sails.jsで$inc演算子を使いたくてnative()でクエリーを実行したところ、ModelのIDを指定するのに手間取ったのでメモ。

実装方法

mongodbモジュールに入っているObjectIDを使用したいのでインストール。mongodbモジュールのObjectIDはbsonモジュールのObjectIDのラッパーなので、インストールするのはbsonでもよい。mongodbの方が今後使いそうな気がしたのでmonbodbにしています。

$ npm install mongodb --save

複数のController/Modelから使いたくなりそうなのでServicesに定義。

api/services/Mongo.js
module.exports = (function() {
  var mongo = require('mongodb');

  var id = mongo.ObjectID;

  return {
    ObjectID: id
  };
})();

native実行時にid(String)をMongo.ObjectID()に渡してやればOK。また、通常のfind()update()でidを指定する場合のkeyはidですが、native()の場合は_idで。mongo的には_idで定義されていて、それをSails.jsがいい感じに変換してくれているので注意。

Message.native(function(err, collection) {
  collection.update({_id: Mongo.ObjectID(id)}, {$inc: {like: 1}}, function(err, results) {
    res.send(200);
  });
});

ちなみに同じことをupdate()でやろうと思うとこうなる。

Message.findOne(id).exec(function(err, message) {
  Message.update({id: id}, {like: message.like + 1}).exec(function(err, message) {
    res.send(200);
  });
});

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