I'm trying to write a Node.js script that updates a collection in MongoDB. I have N patients (their IDs in an array) and for each one I want to update the data in the collection with an object. The documents may not previously exist.
right now i'm doing
MongoClient.connect(url, function (err, db) {
...
var collection = db.collection('datasample_second');
for(var i=0;i<PatientIDs.length; i++){
collection.update({'timestamp' : epoch_sec, 'patientID' : PatientIDs[i] },
updateObj,
{ upsert: true }
);
}
setTimeout(function() {
db.close()
}, 2000);
}); //MongoClient.conect
and I have been forced to put that last timeout there so that the loop can fire the updates to the database and give them time to execute before closing the connection. A priori instead of the timeout I simply had db.close() and of course, I only got the first update and for the others I received a "socket closed" type message.
This fix works as long as I continue with other things, but I don't like it. I've been trying to find something better with the MongoDB Node.js driver documentation, but haven't found anything.
I know that I can pass update as a fourth parameter a callback function, in which I could close the connection. My problem is, again, that it cannot do the close after the first update, but after sending all of them.
Perhaps it would also be easier to do a single update, but as I said, the documents do not always exist (hence the {upsert : true} ) and with each update I want to insert/update as many documents as there are patients in the PatientIDs array.
I tried to use a $in
for the query, but since it doesn't find any preexisting document, mongo does a single update without the patientID field in the object.
Is there a way to detect that the updates have been made and then do the close?