0

How can I save all of the json into my mongoldb? Strangely, only the first value is stored every time. It might be blocking/non-blocking issue.

json = {
  ["name":"Karl","id":"azo0"],
  ["name":"Robert","id":"bdd10"],
  ["name":"Joan","id":"difj90"],
  ["name":"Hallyn","id":"fmak88"],
  ["name":"Michael","id":"vma91"]
};

for(var i = 0; i < json.length; i++){
  id = json[i].id;
  name = json[i].name;

  var ctx = {"id":id,"name":name};
  db.json_db.count(ctx).exec(function(err, count) {
    if(count < 1){
        var model = new User({
           "name":json[i].name,
           "id":json[i].id
        });
        model.save(function(){
            console.log("ok"+i);

        });
    }
  });
};

After inserting, all of datas are filled with ["name":"Karl","id":"azo0"] To check out console.log("ok"+i), it prints always "ok0" not "ok1", "ok2", "ok3"... etc..

How can I prevent this issue?

3

2 Answers 2

1

Incase you're using Async package, this is an best way to solve your problem...

  async.eachSeries(json, (item, done) => {
   let user = new User(
                     {
                        "name":json[i].name,
                         "id":json[i].id
                    },
                    (err, user) => {
                        if(err){
                           // handle err
                        }
                        return done();
                    }
                );
});
Sign up to request clarification or add additional context in comments.

Comments

1

.exec() tells me you're using Mongoose. So your loop can rewritten as:

const json = [
  {name: "Karl", id: "azo0"},
  {name: "Robert", id: "bdd10"},
  {name: "Joan", id: "difj90"},
  {name: "Hallyn", id: "fmak88"},
  {name: "Michael", id: "vma91"}
];

for (const item of json) {
  const count = await db.json_db.count(item).exec()
  if (!count) {
    await new User(item).save()
  }
}

1 Comment

Thank you Mateo, Maybe that’s because everyone is basically used "var" instead of "let", "const". Thanks to you I can resolve my case :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.