SileNT
SileNT

Reputation: 623

validating against mongodb with nodejs

It should be very awesome to use non-blocking code but I'm running out of ideas how to acomplish this task. I have to validate a value by making few db queries like so:

validate = function() {
  var valid = true;
  db.collection('posts').findOne({date: ....}, function(err, post){ 
    if (..) valid = false
  }
  db.collection('posts').findOne({author: .....}, function(err, post){
    if (..) valid = false
  }
  return valid;
}

It is very good that validations can run in concurent manner, but the problem is how to return the final state. Obviously my example will not work. The function will return before db queries execution.

Upvotes: 0

Views: 1555

Answers (2)

kilianc
kilianc

Reputation: 7796

Welcome to the async world.

You should use something like async or fnqueue for your control flow, then you can setup a chain of validations.

function isValid (mainCallback) {
  new FnQueue({
    date: function (callback) {
      if (...) {
        callback();
      } else {
        callback(new Error('what\'s happened here');
      }
    },
    author: function (callback) {
      db.collection('posts').findOne({ author: ..... }, callback);
    }
  },
  function (err, data) {
    mainCallback(Boolean(err)); //you should more than this :)
  },
  1 // concurrency level for serial execution
);

Upvotes: 1

staackuser2
staackuser2

Reputation: 12412

If you are using mongoose, then you can use the validations that are supported in the models. Take a look the validation docs for details and examples.

If you are not using mongoose, then you will need to pass a callback to your validate function, and the callback will receive the boolean. Also, you will need to handle the flow of your function so that they are run in series or parallel, depending on your needs. So if it is in in series, the following would work:

validate = function(callback) {
  var valid = true;
  db.collection('posts').findOne({date: ....}, function(err, post){ 
    if (..) {
      return callback(true);
    }
    db.collection('posts').findOne({author: .....}, function(err, post){
      if (..) callback(false);
    });
  });
}

Upvotes: 0

Related Questions