Help us understand the problem. What is going on with this article?

mongooseでQueryを拡張してみる

More than 5 years have passed since last update.

たまに、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:"文化部"},...]
Why not register and get more from Qiita?
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
Comments
No comments
Sign up for free and join this conversation.
If you already have a Qiita account
Why do not you register as a user and use Qiita more conveniently?
You need to log in to use this function. Qiita can be used more conveniently after logging in.
You seem to be reading articles frequently this month. Qiita can be used more conveniently after logging in.
  1. We will deliver articles that match you
    By following users and tags, you can catch up information on technical fields that you are interested in as a whole
  2. you can read useful information later efficiently
    By "stocking" the articles you like, you can search right away
ユーザーは見つかりませんでした