What I'm trying to accomplish: I query a collection(Conversations) that has a lot of documents in it. For each document/Conversation in the collection, I want to query another Collection(Users), to see if there is an existing User record that matches an ID attribute from that Conversation. So essentially i want to see if a User record exists for a user attached to the Conversation.
Users = { uid:someNumber, bunch of other attributes};
I know this is a problem with the asynchronous nature of node.js. Ive been trying to use async.js to solve this problem with callbacks. But i think i may have it wrong, or am not using it correctly.
The problem is that each conversation item in the conversation array is doing a query for an item, however, because the 'save' hasn't finished yet, the 'find' queries don't ever see that there is record that was already inserted. Here is my code. Maybe I'm doing something obvisouly wrong? So essentially, check the conversation record, if a user record coincides with a user on the conversation record don't do anything, if the user record doesn't exist, create a record.
Conversations.find().limit(1000).exec(function (err, data) {
//data is an array of conversations, i want to loop through each conversation and compare one of the attribute with an attribute on the Users table
async.each(data, function(item, callback1){
//item is a single conversation, on this item there is a participants object that holds two user objects(name, id, type)
async.each(item.participants, function(user, callback2){
//this is where i do my query to see if a user exists
Users.find({uid:user.participantId}).exec(function (err, results){
//if the user doesn't exist then create a user record
if(results.length == 0){
var user = new Users();
user.name =user.participantName;
user.uid = user.participantId;
user.type = user.participantType;
user.save(function(err, result){
console.log(result);
//after it has saved, callback2() so that the second item in the array will query against the Users table
callback2();
})
}
else{
callback2()
})
})
//first item in the conversations array is completed, callback1(), second item should now start
callback1();
});
})