节点回调数据库查询

时间:2017-02-08 16:55:21

标签: node.js mongodb callback

也许我的PHP大脑不允许我做nodejs所有我想要的功能" myfindindb"要返回一个值,是否可以使用nodejs?我知道异步,这是不像瀑布一样工作的原因吗?

var MongoClient = require('mongodb').MongoClient;
var assert = require('assert');
var ObjectId = require('mongodb').ObjectID;
var url = 'mongodb://localhost:27017/exampleDb';
var mysite = '';
var myisfound;
var numItems = '';


function myfindindb(mysite) {

    var findRestaurants = function(db, callback) {

        var cursor = db.collection('restaurants').find({
            "site": mysite
        }).limit(1);

        cursor.each(function(err, doc) {

            assert.equal(err, null);

            var myresults = doc.site;

            return callback(myresults);


        });

       };

    MongoClient.connect(url, function(err, db) {
        assert.equal(null, err);

        findRestaurants(db, function(myresults,callback) {

            console.dir(myresults); //as far as Iv got goo so far

            db.close();

            return callback(myresults); //this bit wont work??
        });


    });

}


var foo = myfindindb('http://google.com');
console.log(foo);

0 个答案:

没有答案