如何将MongoDB结果转换为异步回调

时间:2013-11-03 22:19:10

标签: node.js mongodb

是否可以将此查询的结果导入节点var对象“data”?正确的console.log(结果)出现在控制台中,但结果未返回到数据变量。

var Metric = require('../metric');
var gViews = Object.create(Metric.prototype);
gViews.name = 'g_ref';
gViews.initialData = 0;

gViews.increment = function(results) {



var mongodb = require('mongodb');
var server = new mongodb.Server("127.0.0.1", 27017, {});

new mongodb.Db('xxxx', server, {}).open(function (error, client) {
    client.collection('xxxx_1', function(err, collection) {
        collection.insert({ref_domain:g}, function(err, docs) {
            collection.find({ref_domain: /g/}).count(function(err, results) {
                console.log(results);

            });
        });
    });
});
this.data;
};




module.exports = gViews;

1 个答案:

答案 0 :(得分:0)

你只需要设置它。

var Metric = require('../metric');
var gViews = Object.create(Metric.prototype);
gViews.name = 'g_ref';
gViews.initialData = 0;

gViews.increment = function(results) {
    var mongodb = require('mongodb');
    var server = new mongodb.Server("127.0.0.1", 27017, {});

    new mongodb.Db('xxxx', server, {}).open(function (error, client) {
        client.collection('xxxx_1', function(err, collection) {
            collection.insert({ref_domain:g}, function(err, docs) {
                collection.find({ref_domain: /g/}).count(function(err, results) {
                    gViews.data = results;
                });
            });
        });
    });
};

module.exports = gViews;