I
I
Ilya Beloborodov2016-05-07 01:10:49
MongoDB
Ilya Beloborodov, 2016-05-07 01:10:49

How to choose the right one, and then insert it into the database?

Good evening.
Here I understand with nodejs (3 years with php), and the question arose of how to correctly check the record and if there is no record in the database, then insert it (in a loop).
For example

var data=['word1','word2'];
data.forEach(function(key,val){
      //....
});

actually in the body of the cycle, we check each word for presence in the table, and if it is not there, then we insert a record into the table.
Of course, I can do it in the style of php, I stupidly checked it - I inserted it.
But I'm afraid that on the node it will come out sideways to me. Since each related request is with the previous one, you need to execute in the callback function of the previous request, since nodejs is asynchronous. + server blocking.
Please tell me how to do this simple task.

Answer the question

In order to leave comments, you need to log in

1 answer(s)
S
Super User, 2016-05-07
@sergeystepanov1988

In a forEach loop, you don't. forEach is synchronous and will not wait for the database query to complete.
Theoretically, you can do it with promises, generators and a for loop, or with recursion.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question