3

必要なのは、Schemaメソッドから特定の「親」値を返すことです。

私は2つのスキーマを持っています:

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 ... });ます。

ボーナス回答;)

親の名前を頻繁に使用する場合は、最初のクエリで常にそれを返したい場合があります。Hash_IPのインスタンスのクエリにを入れた場合.populate(_ipset, ['name'])、コードで2層のコールバックを処理する必要はありません。

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がすでに定義されています。楽しみ :)

于 2012-08-02T00:06:30.033 に答える