Note that there are some explanatory texts on larger screens.

plurals
  1. POnodejs: save function in for loop, async troubles
    primarykey
    data
    text
    <p>NodeJS + Express, MongoDB + Mongoose</p> <p>I have a JSON feed where each record has a set of "venue" attributes (things like "venue name" "venue location" "venue phone" etc). I want to create a collection of all venues in the feed -- one instance of each venue, no dupes.</p> <p>I loop through the JSON and test whether the venue exists in my venue collection. If it doesn't, save it. </p> <pre><code>jsonObj.events.forEach(function(element, index, array){ Venue.findOne({'name': element.vname}, function(err,doc){ if(doc == null){ var instance = new Venue(); instance.name = element.vname; instance.location = element.location; instance.phone = element.vphone; instance.save(); } } } </code></pre> <p>Desired: A list of all venues (no dupes).</p> <p>Result: Plenty of dupes in the venue collection. </p> <p>Basically, the loop created a new Venue record for every record in the JSON feed.</p> <p>I'm learning Node and its async qualities, so I believe the for loop finishes before even the first save() function finishes -- so the if statement is always checking against an empty collection. Console.logging backs this claim up.</p> <p>I'm not sure how to rework this so that it performs the desired task. I've tried caolan's async module but I can't get it to help. There's a good chance I'm using incorrectly. </p> <p>Thanks so much for pointing me in the right direction -- I've searched to no avail. If the async module is the right answer, I'd love your help with how to implement it in this specific case.</p> <p>Thanks again!</p>
    singulars
    1. This table or related slice is empty.
    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. 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