0

I want so seed blog posts to my MongoDB database asynchronously (NodeJS, Express, Mongoose), so I have the correct order of the posts for further work on the front end.

I literally tried every async - await combination possible, and the posts keep seeding in chaotic order. I also tried to do it with setTimeout(), also without success.

Here's the code without any wrong async - await attempts:

const Blog = require("../models/blog");
const blogData = require("./blogdata");

function createBlog(data, index) {
  Blog.create(data, (err, blog) => {
    if (err) {
      console.log(err);
    } else {
      blog.save();
      console.log("Seeded Blog Post " + index);
    }
  });
}

function seedDB() {
  Blog.deleteMany({}, (err, res) => {
    if (err) {
      console.log(err);
    } else {
      console.log("removed blogs!");
      blogData.forEach((seed, i) => {
        createBlog(seed, i);
      });
    }
  });
}

module.exports = seedDB;

Actual result:

Seeded Blog Post 0
Seeded Blog Post 6
Seeded Blog Post 5
Seeded Blog Post 13
Seeded Blog Post 10
Seeded Blog Post 2
Seeded Blog Post 8
Seeded Blog Post 9
Seeded Blog Post 1
Seeded Blog Post 11
Seeded Blog Post 7
Seeded Blog Post 3
Seeded Blog Post 4
Seeded Blog Post 12
Seeded Blog Post 14

Desired result:

Seeded Blog Post 0
Seeded Blog Post 1
Seeded Blog Post 2
...
Alex G.
  • 117
  • 2
  • 9
  • Each call is actually "asynchronous", so unless you actually invoke them in a way which guarantees the response is received before invoking the other then the order will never be predictable. *However*, nothing you are doing here requires this "loop" at all. Both `create()` and the preferable `insertMany()` take an array of objects and insert them in sequence. The `create()` does the aforementioned "management of sequential callbacks" for you. The `insertMany()` simply make **one call** to the database and inserts everything you tell it to. – Neil Lunn Apr 07 '19 at 06:15
  • insertMany() solved my problem! cheers – Alex G. Apr 07 '19 at 07:02

0 Answers0