3

我需要的是从 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;
        });
};

没有结果。

在此先感谢您的帮助。

4

1 回答 1

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()or 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。享受 :)

于 2012-08-02T00:06:30.033 回答