javascript - 将 Mongoose 播种脚本变成 promise

标签 javascript mongodb mongoose

我正在努力解决我经常遇到的一个场景:为 MongoDB 数据库播种。所以我得到了以下脚本,我想将其转换为 Promise,最好使用 ES6,但如果是这种情况,我会采用 bluebird 作为答案。 这是我使用 setTimeout 在关闭数据库之前为写入操作提供时间所得到的结果:

// Importing the connection to the `bookshelf` db.
var bookshelfConn = require('./database');

// Importing the Mongoose model we'll use to write to the db.
var Book = require('./models/Book');

// Importing the Data to populate the db.
var books = require('./dataset');

// When the connection is ready, do the music!
bookshelfConn.on('open', function () {
  dropDb(seedDb, closeDb);
});

function dropDb (cb1, cb2) {
  bookshelfConn.db.dropDatabase();
  console.log('Database dropped!');
  cb1(cb2);
}

function seedDb (cb) {
  console.time('Seeding Time'); // Benchmarking the seed process.

  // Warning! Slow IO operation.
  books.forEach(function (book) {
    new Book(book).save(function (err) {
      if (err) console.log('Oopsie!', err);
    });
    console.log('Seeding:', book);
  });

  console.timeEnd('Seeding Time'); // Benchmarking the seed process.

  cb();
}

function closeDb () {
  setTimeout(function () {
    bookshelfConn.close(function () {
      console.log('Mongoose connection closed!');
    });
  }, 1000); // Delay closing connection to give enough time to seed!
}

更新了代码以反射(reflect) zangw 的答案:

// Importing the connection to the `bookshelf` db.
var bookshelfConn = require('./database');

// Importing the Mongoose model we'll use to write to the db.
var Book = require('./models/Book');

// Importing the Data to populate the db.
var books = require('./dataset');

// When the connection is ready, do the music!
bookshelfConn.on('open', function () {
  // Here we'll keep an array of Promises
  var booksOps = [];

  // We drop the db as soon the connection is open
  bookshelfConn.db.dropDatabase(function () {
    console.log('Database dropped');
  });

  // Creating a Promise for each save operation
  books.forEach(function (book) {
    booksOps.push(saveBookAsync(book));
  });

  // Running all the promises sequentially, and THEN
  // closing the database.
  Promise.all(booksOps).then(function () {
    bookshelfConn.close(function () {
      console.log('Mongoose connection closed!');
    });
  });

  // This function returns a Promise.
  function saveBookAsync (book) {
    return new Promise(function (resolve, reject) {
      new Book(book).save(function (err) {
        if (err) reject(err);
        else resolve();
      });
    });
  }
});

最佳答案

请尝试通过new Promise进行操作和 Promise.all

new Promise 创建一个新的 Promise。传入的函数将接收函数resolve和reject作为其参数,可以调用这些函数来密封所创建的promise的命运。

Promise.all 当您想要等待多个 Promise 完成时非常有用。

var bookOps = [];

books.forEach(function (book) {
    bookOps.push(saveBookAsync(book));
});

Promise.all(bookOps).then(function() {
   bookshelfConn.close(function () {
      console.log('Mongoose connection closed!');
    });
});

function saveBookAsync(book) {
    return new Promise(function(resolve, reject) {
        new Book(book).save(function(err) {
            if (err)
                reject(err);
            else
                resolve();
        })
    });
}

关于javascript - 将 Mongoose 播种脚本变成 promise ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35662618/

相关文章:

node.js - 类型错误 : Cannot read property '_id' of undefined in Angular4

mongodb - 未在ElasticSearch中添加Mongo '_id'字段

node.js - 如何在 Mongoose 中执行 id 数组查询?

mongodb - 如何在 Mongoose 中获取收藏列表?

javascript - Firebase pubsub 函数计划无效的计划或时区

javascript - 从 .json URL 获取数据并使用 Javascript/JQuery 将其显示在 HTML 中

javascript - Nodejs Mongoose 无法更新数据库中的值

javascript - 从 javascript 调用 Google 云打印/搜索 API

mysql - mongodb - 寻找类似于 mysql 的 "id in(1,2,3,4)"的选择查询

node.js - 由于某种原因,bulkWrite 和 arrayFilter 没有修改文档。 MongoDB 和 Mongoose