One approach you can take is to modifying your followSchema to have the following
field as an array and use the concept of population:
var mongoose = require('mongoose')
, Schema = mongoose.Schema
var userSchema = Schema({
_id: Number,
name: String,
age: Number,
followers: [{ type: Schema.Types.ObjectId, ref: 'Follow' }]
});
var followSchema = Schema({
_user: { type: Number, ref: 'User' },
following: [{ type: Number, ref: 'User' }]
});
var Follow = mongoose.model('Follow', followSchema);
var User = mongoose.model('User', userSchema);
which you can then query with the some sample users. As an example guide (untested):
var user1_id = 1,
user2_id = 2,
user3_id = 3,
user1_following = [],
user2_following = [];
var user1 = new User({ _id: user1_id, name: 'User1', age: 31 });
var user2 = new User({ _id: user2_id, name: 'User2', age: 32 });
var user3 = new User({ _id: user3_id, name: 'User3', age: 32 });
user3.save(function (err) {
if (err) return handleError(err);
})
user1.save(function (err) {
if (err) return handleError(err);
var follower3 = new Follow({ _user: user3_id });
follower3.save(function (err) {
if (err) return handleError(err);
// thats it!
});
})
user2.save(function (err) {
if (err) return handleError(err);
var follower3 = new Follow({ _user: user3_id });
follower3.save(function (err) {
if (err) return handleError(err);
// thats it!
});
})
Follow
.find({ _user: user1_id })
.exec(function (err, following) {
if (err) return handleError(err);
user1_following = following;
})
Follow
.find({ _user: user2_id })
.exec(function (err, following) {
if (err) return handleError(err);
user2_following = following;
})
You can then use Underscore's intersection()
which will give you a list of values present in both arrays.
var commonFollowings = _.intersection(user1_following, user2_following);
// In the example above, commonFollowings => [3]