2012-08-01 36 views
3

我需要做的是從一個架構方法返回一個特定的「父」值:在貓鼬模式迴歸「母體」收集特定值

我有兩個模式:

var IP_Set = new Schema({ 
    name: String 
}); 

var Hash_IP = new Schema({ 
    _ipset  : { 
     type: ObjectId, 
     ref: 'IP_Set' 
    }, 
    description : String 
}); 

Hash_IP模式我想有以下方法:

Hash_IP.methods.get_parent_name = function get_parent_name() { 
    return "parent_name"; 
}; 

所以當我運行:

var hash_ip = new Hash_IP(i); 
console.log(hash_ip.get_parent_name()) 

我可以得到相關Hash_IP實例的IP_Set名稱值。

到目前爲止,我有以下的定義,但我不能設法返回名稱:

Hash_IP.methods.get_parent_name = function get_parent_name() { 
    this.model('Hash_IP').findOne({ _ipset: this._ipset }) 
     .populate('_ipset', ['name']) 
     .exec(function (error, doc) { 
      console.log(doc._ipset.name); 
     }); 
}; 

我已經試過:

Hash_IP.methods.get_parent_name = function get_parent_name() { 
    this.model('Hash_IP').findOne({ _ipset: this._ipset }) 
     .populate('_ipset', ['name']) 
     .exec(function (error, doc) { 
      return doc._ipset.name; 
     }); 
}; 

沒有結果。

在此先感謝您的幫助。

回答

3

我相信你非常接近。你的問題是不是對這個很清楚,但我認爲

.populate('_ipset', ['name']) 
.exec(function (error, doc) { 
    console.log(doc._ipset.name); 
}); 

工作和

.populate('_ipset', ['name']) 
.exec(function (error, doc) { 
    return doc._ipset.name; 
}); 

是不是?

不幸的是,異步return無法按照您希望的方式工作。

.exec調用您的回調函數,該函數返回名稱。儘管如此,這不會返回名稱作爲get_parent_name()的返回值。那樣就好了。 (想象一下return return name語法)。在回調

進入get_parent_name()這樣的:

Hash_IP.methods.get_parent_name = function get_parent_name(callback) { 
    this.model('Hash_IP').findOne({ _ipset: this._ipset }) 
     .populate('_ipset', ['name']) 
     .exec(callback); 
}; 

現在,您可以在代碼中使用instance_of_hash_ip.get_parent_name(function (err, doc) { ... do something with the doc._ipset.name ... });

獎金的答案;)

如果你用你的父母的名字很多,你可能想永遠與你的初始查詢返回。如果您將.populate(_ipset, ['name'])放入查詢中以查找Hash_IP的實例,那麼您將不必在代碼中處理兩層回調。

只需將find()findOne(),然後將populate()轉換爲模型的一個很好的靜態方法。獎金答案

獎金例如:)

var Hash_IP = new Schema({ 
    _ipset  : { 
     type: ObjectId, 
     ref: 'IP_Set' 
    }, 
    description : String 
}); 

Hash_IP.statics.findByDescWithIPSetName = function (desc, callback) { 
    return this.where('description', new RegExp(desc, 'i')) 
     .populate('_ipset', ['name']) //Magic built in 
     .exec(cb) 
}; 

module.exports = HashIpModel = mongoose.model('HashIp', Hash_IP); 

// Now you can use this static method anywhere to find a model 
// and have the name populated already: 

HashIp = mongoose.model('HashIp'); //or require the model you've exported above 
HashIp.findByDescWithIPSetName('some keyword', function(err, models) { 
    res.locals.hashIps = models; //models is an array, available in your templates 
}); 

每個模型實例現在已經models._ipset.name已定義。享受:)

+0

感謝您的獎金答案! :)你在第一個答案中註明的正是我所需要的。我想這樣做,我不需要通過回調,因爲你指向Hash_IP.methods.get_parent_name方法的例子,因爲其他應用程序的要求:(你可以發佈獎勵答案的獎勵例子:D。提前致謝! – diosney 2012-08-02 00:39:37

+0

完成後,看看是否有幫助:) – rdrey 2012-08-02 00:53:30

+0

我差點忘了:+1獎金答案hehehe:D – diosney 2012-08-02 01:00:38