NodeJS 및 MongoDB를 처음 사용했습니다. nodejs에서 비동기 함수를 사용하여 문서를 업데이트하는 방법이 있습니까? 나는 _id, 이름, 등록자와 같은 웹 사이트 모음을 가지고있다. 비동기 함수를 사용하여 레지스트라에 값을 삽입하려고합니다. 이 함수는 시스템 호출이며, 나는 원하는 출력을 파싱한다. 코드를 실행하면 async 함수가 원하는 정보를 기록하지만 데이터베이스에 저장하지는 않습니다. 이 문제를 어떻게 해결할 수 있을지에 대한 제안이 있으십니까? 감사. 핵심에Nodejs MongoDB 비동기 함수로 문서 업데이트
/*
* { _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);
});
}
[이 좋은 axample] (https://github.com/TechEmpower/FrameworkBenchmarks :
하는 비동기 될 함수를 만듭니다 /blob/master/nodejs/hello.js) 비동기 작업. – zishe