2014-12-16 2 views
-1

Я работаю над модулем, который добавляет дружеские отношения к схеме.this.find (...) никогда не достигает обратного вызова в статическом методе

Я в основном пытаюсь делать то, что this guy пытается сделать (что, AFAIK, должно работать - что обескураживает)

Почему find(...) в FriendshipSchema.statics.getFriends никогда не достигая свой обратный вызов?

EDIT - Пожалуйста, позвольте мне объяснить ожидаемый поток выполнения ...

accounts.js внутри:

  1. требует от «друзей-оф-друзей модуля (нагрузки friends-of-friends/index.js), которые
    1. требует: friends-of-friends/friendship.js который экспортирует функцию, которая создает FriendshipSchema, добавляет статические методы, возвращает Friendship модель.
    2. требует friends-of-friends/plugin.js, который экспортирует плагин mongoose, который добавляет статические и методы экземпляра в `AccountSchema.
  2. использует FriendsOfFriends.plugin (см friends-of-friends/index.js), чтобы плагин функциональности от friends-of-friends/plugin.js
  3. определяет AccountSchema.statics.search, который вызывает this.getFriends.
    Поскольку this относится к Account модели, когда он собран, и так как плагин добавлен schema.statics.getFriends, вызывая this.getFriends внутри AccountSchema.statics.search будет вызывать schema.statics.getFriends, как определено в friends-of-friends/plugin.js, который будет вызывать Friendship.getFriends (определяется FriendshipSchema.statics.getFriends в friends-of-friends/friendship.js), который вызывает this.find(...), который должен перевести в Friendship.find (...) `
  4. после получения документа счета, я называю account.search('foo', function (...) {...});, но, как вы можете видеть в FriendshipSchema.statics.getFriends, метод find выполняет, но обратный вызов никогда не вызывается и программа зависает :(

я не получаю никаких ошибок, так что я знаю, что это логическая задача, но я не знаю, почему вещи становятся повесила, где они ...

EDIT - см мой ответ ниже , Мне также пришлось скомпилировать модели, прежде чем я смог называть их find.

account.js

var mongoose = require('mongoose'), 
    passportLocalMongoose = require('passport-local-mongoose'); 

var FriendsOfFriends = require('friends-of-friends')(); 

// define the AccountSchema 
// username, password, etc are added by passportLocalMongoose plugin 
var AccountSchema = new mongoose.Schema({ 
    created:  { type: Date,  default: Date.now     }, 
    profile: { 
     displayName: { type: String,  required: true,  unique : true, index: true  }, 
     firstName:  { type: String,  required: true,  trim: true,  index: true  }, 
     lastName:  { type: String,  required: true,  trim: true,  index: true  }, 
    } 
}); 

// plugin the FriendsOfFriends plugin to incorporate relationships and privacy 
AccountSchema.plugin(FriendsOfFriends.plugin, FriendsOfFriends.options); 

AccountSchema.statics.search = function (userId, term, done) { 
    debug('search') 

    var results = { 
      friends: [], 
      friendsOfFriends: [], 
      nonFriends: [] 
     }, 
     self=this; 

    this.getFriends(userId, function (err, friends) { 

     // never reaches this callback! 

    }); 

}; 

AccountSchema.methods.search = function (term, done) { 
    debug('method:search') 
    AccountSchema.statics.search(this._id, term, done); 
}; 

module.exports = mongoose.model('Account', AccountSchema); 

друзей-из-друзей/index.js

/** 
* @author Jeff Harris 
* @ignore 
*/ 

var debug = require('debug')('friends-of-friends'); 
    friendship = require('./friendship'), 
    plugin = require('./plugin'), 
    privacy = require('./privacy'), 
    relationships = require('./relationships'), 
    utils = require('techjeffharris-utils'); 

module.exports = function FriendsOfFriends(options) { 

    if (!(this instanceof FriendsOfFriends)) { 
     return new FriendsOfFriends(options); 
    } 

    var defaults = { 
     accountName: 'Account', 
     friendshipName: 'Friendship', 
     privacyDefault: privacy.values.NOBODY 
    }; 

    this.options = utils.extend(defaults, options); 

    /** 
    * The Friendship model 
    * @type {Object} 
    * @see [friendship]{@link module:friendship} 
    */ 
    this.friendship = friendship(this.options); 

    /** 
    * mongoose plugin 
    * @type {Function} 
    * @see [plugin]{@link module:plugin} 
    */ 
    this.plugin = plugin; 

    debug('this.friendship', this.friendship); 

}; 

друзей-о-друзей/friendship.js

var debug = require('debug')('friends-of-friends:friendship'), 
    mongoose = require('mongoose'), 
    privacy = require('./privacy'), 
    relationships = require('./relationships'), 
    utils = require('techjeffharris-utils'); 

module.exports = function friendshipInit(options) { 

    var defaults = { 
     accountName: 'Account', 
     friendshipName: 'Friendship', 
     privacyDefault: privacy.values.NOBODY 
    }; 

    options = utils.extend(defaults, options); 

    debug('options', options); 

    var ObjectId = mongoose.Schema.Types.ObjectId; 

    var FriendshipSchema = new mongoose.Schema({ 
     requester: { type: ObjectId, ref: options.accountName, required: true, index: true }, 
     requested: { type: ObjectId, ref: options.accountName, required: true, index: true }, 
     status: { type: String, default: 'Pending', index: true}, 
     dateSent: { type: Date, default: Date.now, index: true }, 
     dateAccepted: { type: Date, required: false, index: true } 
    }); 

    ... 

    FriendshipSchema.statics.getFriends = function (accountId, done) { 
     debug('getFriends') 

     var model = mongoose.model(options.friendshipName, schema), 
      friendIds = []; 

     var conditions = { 
      '$or': [ 
       { requester: accountId }, 
       { requested: accountId } 
      ], 
      status: 'Accepted' 
     }; 

     debug('conditions', conditions); 

     model.find(conditions, function (err, friendships) { 
      debug('this callback is never reached!'); 

      if (err) { 
       done(err); 
      } else { 
       debug('friendships', friendships); 

       friendships.forEach(function (friendship) { 
        debug('friendship', friendship); 

        if (accountId.equals(friendship.requester)) { 
         friendIds.push(friendship.requested); 
        } else { 
         friendIds.push(friendship.requester); 
        } 

       }); 

       debug('friendIds', friendIds); 

       done(null, friendIds); 
      } 

     }); 

     debug('though the find operation is executed...'); 
    }; 

    ... 

    return mongoose.model(options.friendshipName, FriendshipSchema); 
}; 

друзей-of друзья/плагин.js

var debug = require('debug')('friends-of-friends:plugin'), 
    mongoose = require('mongoose'), 
    privacy = require('./privacy'), 
    relationships = require('./relationships'), 
    utils = require('techjeffharris-utils'); 

module.exports = function friendshipPlugin (schema, options) { 

    var defaults = { 
     accountName: 'Account', 
     friendshipName: 'Friendship', 
     privacyDefault: privacy.values.NOBODY 
    }; 

    options = utils.extend(defaults, options); 

    var Friendship = mongoose.model(options.friendshipName); 

    ... 

    schema.statics.getFriends = function (accountId, done) { 
     debug('getFriends') 

     var model = mongoose.model(options.accountName, schema); 

     var select = '_id created email privacy profile'; 

     Friendship.getFriends(accountId, function (err, friendIds) { 
      if (err) { 
       done(err); 
      } else { 
       model.find({ '_id' : { '$in': friendIds } }, select, done); 
      } 
     }); 
    }; 

    ... 

    schema.methods.getFriends = function (done) { 
     schema.statics.getFriends(this._id, done); 
    }; 
}; 
+0

Для человека, который дал мне -1, будет вам пожалуйста, просветите меня своими рассуждениями или предложением улучшить мой вопрос. – techjeffharris

ответ

0

Вопрос был связан с тем, какой экземпляр мангусты требуется.

В моем главном приложении, я требую мангуста от app/node_modules/mongoose тогда моего friends-of-friends модуля - перечислив мангуст, как зависимость в package.json --was, требующего мангуст от app/node_modules/friends-of-friends/node_modules/mongoose, который создал две отдельных экземпляры мангуста, которые делали вещи не работает.

я удалил мангуста, как зависимость, убрана вложенную папку node_modules и vioala, она работает, опять же :)

должны иметь RTFM

app/ 
| lib/ 
| node_modules/ 
| | mongoose/    <-- main app required here 
| | friends-of-friends/ 
| | | node_modules/  <-- deleted; mongoose was only dep 
| | | | mongoose/  <-- friends-of-friends module required here 
| server.js 
Смежные вопросы