简体   繁体   English

使用nodejs针对mongodb进行验证

[英]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. 该函数将在执行db查询之前返回。

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. 您应该为控制流使用asyncfnqueue之类的东西,然后才能设置验证链。

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
);

If you are using mongoose , then you can use the validations that are supported in the models. 如果使用mongoose ,则可以使用模型中支持的验证。 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. 如果您不使用猫鼬,则需要将回调传递给validate函数,并且该回调将接收布尔值。 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);
    });
  });
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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