Я работаю над модулем, который добавляет дружеские отношения к схеме.this.find (...) никогда не достигает обратного вызова в статическом методе
Я в основном пытаюсь делать то, что this guy пытается сделать (что, AFAIK, должно работать - что обескураживает)
Почему find(...)
в FriendshipSchema.statics.getFriends
никогда не достигая свой обратный вызов?
EDIT - Пожалуйста, позвольте мне объяснить ожидаемый поток выполнения ...
accounts.js
внутри:
- требует от «друзей-оф-друзей модуля (нагрузки
friends-of-friends/index.js
), которые- требует:
friends-of-friends/friendship.js
который экспортирует функцию, которая создаетFriendshipSchema
, добавляет статические методы, возвращаетFriendship
модель. - требует
friends-of-friends/plugin.js
, который экспортирует плагин mongoose, который добавляет статические и методы экземпляра в `AccountSchema.
- требует:
- использует
FriendsOfFriends.plugin
(смfriends-of-friends/index.js
), чтобы плагин функциональности отfriends-of-friends/plugin.js
- определяет
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 (...) ` - после получения документа счета, я называю
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);
};
};
Для человека, который дал мне -1, будет вам пожалуйста, просветите меня своими рассуждениями или предложением улучшить мой вопрос. – techjeffharris