Note that there are some explanatory texts on larger screens.

plurals
  1. PO
    primarykey
    data
    text
    <p>First, I recommend you to switch from your current <code>mongodb</code> module to something more comfortable, such as:</p> <ul> <li><a href="https://github.com/LearnBoost/monk" rel="nofollow">monk</a></li> <li><a href="https://github.com/kissjs/node-mongoskin" rel="nofollow">mongoskin</a></li> <li><a href="http://mongoosejs.com/" rel="nofollow">mongoose</a></li> </ul> <p>I'll be using <code>monk</code> in my example, by it may be easily adapted for any <code>mongodb</code> module, including <a href="https://github.com/mongodb/node-mongodb-native" rel="nofollow">native mongodb node driver</a>.</p> <p>As for your problem, you may solve it with any module for asynchronous control flow management, such as:</p> <ul> <li><a href="https://github.com/caolan/async" rel="nofollow">async</a></li> <li>most <a href="https://github.com/promises-aplus/promises-spec/blob/master/implementations.md" rel="nofollow">A+/promises</a>, e.g. <a href="https://github.com/cujojs/when" rel="nofollow">when.js</a></li> </ul> <p>Here's an example of solving your problem with <code>async.js</code>:</p> <pre><code>checkDialog: function (data, callback) { var db = require('monk')('localhost/messages'); var dialogsDb = db.get('dialog'); var interlocutorsArray = JSON.parse(data); async.concat(interlocutorsArray, function (item, next) { var query = { owner: item.owner_user_id viewer: item.viewer_user_id }; dialogsDb.find(query, function (err, docs) { if (err) return next(err); if (docs &amp;&amp; docs.length &gt; 0) { next(null, docs); } else { dialogsDb.insert(query, function (err, inserting) { next(err, [inserting]); }) } }) }, function (err, items) { if (err) throw err; // it's best to handle errors without throwing them var dialogsId = {}; for (var item, i = 0; i &lt; items.length; i++) { item = items[i]; dialogsId[item._id] = { owner: item.owner, viewer: item.viewer }; } callback(dialogsId); }) } </code></pre>
    singulars
    1. This table or related slice is empty.
    plurals
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. This table or related slice is empty.
    1. VO
      singulars
      1. This table or related slice is empty.
    2. VO
      singulars
      1. This table or related slice is empty.
    3. VO
      singulars
      1. This table or related slice is empty.
 

Querying!

 
Guidance

SQuiL has stopped working due to an internal error.

If you are curious you may find further information in the browser console, which is accessible through the devtools (F12).

Reload