在Mongoose Schema中返回“父”集合的特定值

时间:2012-08-01 23:22:04

标签: node.js schema express return-value mongoose

我需要从Schema方法返回特定的“父”值:

我有两个模式:

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())

我可以获取关联的IP_Set实例的Hash_IP名称值。

到目前为止,我有以下定义,但我无法返回名称:

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;
        });
};

没有结果。

提前感谢您的帮助。

1 个答案:

答案 0 :(得分: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。享受:)