1

I'm new to NodeJS and MongoDB. Is there a way to update a document using asynchronous functions in nodejs? I have a collection of websites with documents: _id, name and registrant. I want to insert a value in registrar using an asynchronous function. The function is a system call, and I just parse the output that I want. Running the code, the async function logs the information I want but does not store in the database. Any suggestions on how I can solve this? Thanks.

/*
 * { _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

1 Answer 1

1

Start one process on core:

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

Create function to be async:

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;
Sign up to request clarification or add additional context in comments.

1 Comment

You should change it with your code, it's just a concept:)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.