LoginSignup
3
4

More than 5 years have passed since last update.

mongooseでQueryを拡張してみる

Posted at

たまに、mongooseのQueryで取得したオブジェクトをSQLのように1レコードにしたい時があるので、mongooseのQueryを拡張しようと試みたところ、意外と簡単に拡張することができた。
ただの遊びのつもりなので、今度本気でプラグインを作ってみたい。

mongoose-plugin.js
var sync = require('synchronize');/*同期処理のモジュール*/
Query.prototype.flatten = function(key,callback){
    var docs = sync.await(this.find(sync.defer()));
    var data = docs;
    for(var i = 0,n = data.length; i < n; i++){
        var obj = data[i][key];
        for(var t in obj){
            if(t == "_id")
                data[i][key+t] = obj[t];
            else
                data[i][t] = obj[t];
        }
        delete data[i][key];
    }
    if(callback)
        return callback(null,docs);
    else
        return docs;                        
}
userSchema
{name:String,mail:String,pw:String,
target:{type:ObjectId,ref:'target'}}
targetSchema
{targetname:String,kind:String}
usage
user.find({username:name})
.populate("target").lean()
.flatten("target",function(err,docs){
    console.log(docs);
});

するとこのような結果になってdocsがかえってくる。

result.json
[{name:"steelydylan",mail"XXX@gmail.com",pw:"****",
targetname:"ライフル部",kind:"文化部"},...]
3
4
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
3
4