(First of, explaining complex things in English is not really a strength of mine. I have tried to be as elaborate as possible so you might understand my problem).
I recently started digging into Mongoose for a node.js-based web app I'm working on. The usual, including an user system where each user is able to follow others. If userA follows userB, it adds a new document to the Connections collection, containing userA's "_id" as "idA" and userB's "_id" as "idB".
Users collection
{
"_id" : ObjectId("HarrysID"),
"name" : "Harry"
"password": "..."
}
{
"_id" : ObjectId("TomsID"),
"name" : "Tom"
"password": "..."
}
Connections collection
{
"_id" : ObjectId("5ac130e9d6239151a86035c7"),
"idA" : ObjectId("TomsID"),
"idB" : ObjectId("HarrysID"),
}
{
"_id" : ObjectId("5ac13102d6239151a86035c8"),
"idA" : ObjectId("HarrysID"),
"idB" : ObjectId("TomsID"),
}
What I try to achieve
Without getting into much detail, you might know about Twitter's system, where you can only write a message to an user if this user followed you back.
This obviously can easily done with two requests:
Does Harry follow Tom? If true, does user Tom follow Harry? => Harry can contact Tom!.
Now I want to do this on a bigger scale. I need a function which returns a list of users someone can contact.
I have already done it using a recursive function, which first finds every document in Connections where "idA" is the current user. Then, it fetches through the returned list of connections and checks whether a document exists where "idB" follows "idA" – if not, it removes the document from the final resulting array. I would not consider myself being a database pro, but this system seems really inefficient in multiple ways and is pretty much a magnet for all kinds of errors.
Is there a better way for doing this? I am sure that aggregate(), project() and / or group() will be helpful, but how?
What should it somewhat look like in the end?
Since Harry follows Tom, and Tom follows Harry, Harry's contacts should contain Tom('s following).
listContacts(ObjectId("HarrysID"), function(err, result) {
console.log("Harry can message these users = ", result);
/* Harry can message these users =
[{
"_id" : ObjectId("5ac13102d6239151a86035c8"),
"idA" : ObjectId("HarrysID"),
"idB" : ObjectId("TomsID"),
}]
*/
});
Thank you for taking your time!