简体   繁体   中英

How do I query in Mongo?

I'm beating my head against a wall trying to query Mongo successfully.

This code:

    async.waterfall([
        function(callback){
            cursor = db.collection(collection).findOne(query)
            callback(null);
        },
        function(callback){
            console.log("Result is:" + cursor);
            console.log(JSON.stringify(cursor));
            callback(null);
        }
    ]);

Produces the following output:

result is:[object Object]
{}

Why? There is a document that it should be finding in the collection.

As a followup question, how do I get to see what

[object Object] 

is?

Basically you should wait for your query to complete and then call the callback and expect any result:

        async.waterfall([
            function(callback){
                db.collection(collection).findOne(query, function(err, result) {
                  callback(err, result); // if there is no err, it will be null
                });
                // the above can be simplified to just                                    
                // db.collection(collection).findOne(query, callback);
                // since findOne callback and current function callback have the same arguments
            },
            function(result, callback) {
                // use comma here to automatically doing JSON.stringiry(result)
                console.log("Result is:", result);
                callback();
            }
        ], function(err) {
           // here is your final callback where you know that async.waterfall 
           // is finished (with or without error)
        });

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM