Nodejs MongoDB使用异步函数更新文档

时间:2014-04-09 00:26:43

标签: node.js mongodb asynchronous

我是NodeJS和MongoDB的新手。有没有办法在nodejs中使用异步函数更新文档?我有一系列包含文档的网站:_id,名称和注册人。我想使用异步函数在注册器中插入一个值。该函数是一个系统调用,我只是解析我想要的输出。运行代码时,async函数会记录我想要的信息,但不会存储在数据库中。关于如何解决这个问题的任何建议?感谢。

/*
 * { _id: 53448014b15c693931000002,
 *   name: 'google.com',
 *   registrant: 'defaultval' } */

var MongoClient = require('mongodb').MongoClient;
var ObjectID = require('mongodb').ObjectID;
var id = '53448014b15c693931000002';
var domain = 'google.com';
MongoClient.connect('mongodb://127.0.0.1:27017/mydb', function(err, db) {
    if (err) throw err;         
    var collection = db.collection('websites');

    collection.findAndModify({_id:new ObjectID(id)}, 
            {}, 
            {$set: {registrant: test(domain, function (output) {
                var t = output.split("\n");
                for (var i = 0; i < t.length; ++i) {
                    if (t[i].indexOf("Registrant Organization:") != -1) {
                        console.log(t[i].substring(t[i].indexOf(":") + 2, t[i].length));//prints correct value, need this to store in registrant doc
                        return t[i].substring(t[i].indexOf(":") + 2, t[i].length);
                    }               
                }   
            })}}, 
            {}, 
            function(err, object) {
                if (err) console.log(err.message);
                else { 
                    console.log(object);
                }
            db.close();
        });
});

var test = function(domain, cb) {
  var sys = require('sys');
  var exec = require('child_process').exec;
  var child = exec('whois ' + domain, function(error, stdout, stderr) {
      cb(stdout);
  });
}

1 个答案:

答案 0 :(得分:1)

在核心上启动一个流程:

var cluster = require('cluster')
  , numCPUs = require('os').cpus().length
  , windows = require('os').platform() == 'win32';

if(cluster.isMaster) {
  // Fork workers.
  for (var i = 0; i < numCPUs; i++) {
    cluster.fork();
  }

  cluster.on('exit', function(worker, code, signal) {
    console.log('worker ' + worker.pid + ' died');
  });

  return;
}

创建异步函数:

function mongodbDriverQuery(callback) {
  collection.findOne({ id: getRandomNumber()}, function(err, world) {
    callback(err, world);
  });
}

http.createServer(function (req, res) {
  // JSON response object
  var hello = {message: "Hello, World!"};
  var helloStr = "Hello, World!";
  var path = url.parse(req.url).pathname;

  // mysql on windows is not supported
  if (windows && (path.substr(0, 3) == '/my' || path == '/update')) {
    path = '/doesntexist';
  }

  switch (path) {
  case '/mongodbdriver':
    // Database Test
    var values = url.parse(req.url, true);
    var queries = values.query.queries || 1;
    var queryFunctions = new Array(queries);

    for (var i = 0; i < queries; i += 1) {
      queryFunctions[i] = mongodbDriverQuery;
    }

    res.writeHead(200, {'Content-Type': 'application/json; charset=UTF-8'});

    // and run it
    async.parallel(queryFunctions, function(err, results) {
      if (queries == 1) {
        results = results[0];
      }
      res.end(JSON.stringify(results));
    });
    break;