异步播种mongo数据库

时间:2019-04-07 05:58:50

标签: javascript node.js express asynchronous mongoose

我想让博客帖子异步地播种到我的MongoDB数据库中(NodeJS,Express,Mongoose),所以我有正确的帖子顺序以在前端进行进一步的工作。

我实际上尝试了每个异步操作-等待可能的组合,并且帖子继续以混乱的顺序播种。我也尝试使用setTimeout()来完成此操作,但也没有成功。

这是没有任何错误异步的代码-等待尝试:

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;

实际结果:

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

所需结果:

Seeded Blog Post 0
Seeded Blog Post 1
Seeded Blog Post 2
...

0 个答案:

没有答案