2012-08-01 40 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