The whole function allPrototypes(userModel, callback)
gets called for every userModel in the DB, let's say 100 times.
My Problem: Because of the asynchronous JS the function addJobToUser(userId, jobId)
is called only with the last of the 100 userModels.
So addJobToUser
is called 100 times but not with userModel 1 to 100, but with userModel 100 every single time (as you can see on my comments).
I can imagine that the problem is the asynchronous JS.
Do you guys have a solution for my problem?
function allPrototypes(userModel, callback){
// HERE console.log() -> USER MODELS 1-100
var MongoClient = mongo.MongoClient;
var url = 'mongodb://localhost:27017/uniyapp';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
var cursor = db.collection('jobprototypes').find();
cursor.each(function (err, doc) {
if(doc != null){
console.log(userModel.id);
// create prototypeModel
var jobPrototypeModel = new prototype.emptyPrototype();
jobPrototypeModel.attributes = doc['attributes'];
jobPrototypeModel.contributors = doc['contributors'];
jobPrototypeModel.id = doc['_id'];
// now calculate the similarity between prototypemodel and usermodel
// HERE console.log() -> USER MODELS 1-100
console.log(callback(jobPrototypeModel, userModel));
if(callback(jobPrototypeModel, userModel) <= threshold){
addJobToUser(userModel.id, jobPrototypeModel.id);
}
}
});
db.close();
});
}
function addJobToUser(userId, jobId){
var MongoClient = mongo.MongoClient;
var url = 'mongodb://localhost:27017/uniyapp';
MongoClient.connect(url, function(err, db) {
if (err) throw err;
db.collection('jobusers').update({_id:userId}, {'$set' : {jobs: ['nevermind']}});
db.close();
});
}