简体   繁体   中英

async.series with mongoose

var mongoose = require('mongoose');
var mongoDB = "mongodb://jananton:password1@ds020168.mlab.com:20168/test_database";
var User = require('./models/User.js');
var async = require('async');

function establishConnection() {
  mongoose.connect(mongoDB, {
    useNewUrlParser: true
  }).then(
    () => {
      console.log("Connection successful")
    },
    (err) => {
      console.log("Warning!" + err)
    }
  );
  mongoose.Promise = global.Promise;
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));
}

let users = [];

function createUser(user_name, user_status, user_position) {
  var newUser = new User({
    Name: user_name,
    _id: new mongoose.Types.ObjectId(),
    Status: user_status,
    Position: user_position
  });
  newUser.save((err) => {
    if (err) {
      console.log(err);
    }
  });
  console.log(newUser.Name);
  users.push(newUser);
};

//Call both functions, starting with establishConnection
async.series([
    establishConnection,
    createUser("Andy", "Administrator", "Whatever"),
  ],
  function(err, res) {
    mongoose.connection.close();
  })

In the code above, I just connect to a my MongoDB database hosted on mLab via the establishConnection() method. The second function, createUser, creates an document and saves it to the database. Both functions are then calles from inside the async.series() function with the console output of

Andy
Connection successful

I dont`t understand why Andy is output first, only then Connection successful is logged, since establishConnection() comes before createUser(). Additionally, mongoose won't close the connection (see the callback function of the async.series function). Can someone explain me why?

So you need to correct the usage of async.series. async.series requires each function to call the callback function when its execution is completed, hence the series works properly.

async.series([
    function(callback) {
        // do some stuff ...
        callback(null, 'one');
    },
    function(callback) {
        // do some more stuff ...
        callback(null, 'two');
    }
],
// optional callback
function(err, results) {
    // results is now equal to ['one', 'two']
});

so in your case you need to do it like this,

var mongoose = require('mongoose');
var mongoDB = 
 "mongodb://jananton:password1@ds020168.mlab.com:20168/test_database";
var User = require('./models/User.js');
var async = require('async');

function establishConnection(callback) {
  mongoose.connect(mongoDB, {
    useNewUrlParser: true
  }).then(
    () => {
      console.log("Connection successful")
      callback(null, "Connection successful");
    },
    (err) => {
      console.log("Warning!" + err)
      callback(err);
    }
  );
  mongoose.Promise = global.Promise;
  var db = mongoose.connection;
  db.on('error', console.error.bind(console, 'MongoDB connection error:'));
}

let users = [];

function createUser(user_name, user_status, user_position, callback) {
  var newUser = new User({
    Name: user_name,
    _id: new mongoose.Types.ObjectId(),
    Status: user_status,
    Position: user_position
  });
  newUser.save((err) => {
    if (err) {
      console.log(err);
      return callback(err);
    }
  });
  console.log(newUser.Name);
  users.push(newUser);
  return callback(null, newUser);
};

//Call both functions, starting with establishConnection
async.series([
    establishConnection,
    createUser("Andy", "Administrator", "Whatever", callback),
  ],
  function(err, res) {
    mongoose.connection.close();
  })

Hope this might help you.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM