简体   繁体   English

MongoDB发现返回零结果

[英]MongoDB find returning zero results

I know this will be something small I'm missing, but would appreciate the help. 我知道这将是我所缺少的小东西,但会感谢您的帮助。

Here is my test script (node.js) 这是我的测试脚本(node.js)


var MongoClient = require('mongodb').MongoClient;

MongoClient.connect('mongodb://localhost:27017/myTestDB',
    function (err, db) {
        if (err)
            debugger;
        else {            
            db.collection('test', function (err, collection) {

                collection.save({ name: "danny" }, function () { debugger;});

                collection.find(function (err, results) {
                    if(results.items.length == 0){
                       ///======> always = 0 !!!! WHY?!!!!
                        debugger;
                    }
                });
            });

        }
        db.close();
    });

feel free to start your answer with "duh!" 随时以“ duh”开始回答。

UPDATE : you also need to move your db.close(); 更新 :您还需要移动db.close(); call inside the find callback or you're closing the connection before you're done with it. find回调内部调用,或者在完成连接之前先关闭连接。

In your example, results is a cursor, not an array of docs, so you need to call toArray on it to iterate over the cursor and get the array of docs. 在您的示例中, results是游标,而不是文档数组,因此您需要在其上调用toArray以遍历游标并获取文档数组。 But you also need to put your find call inside the save callback. 但是您还需要将find调用放入save回调中。 Otherwise the find is executing before the save has completed. 否则, find将在save完成之前执行。

So something like this instead: 所以像这样:

collection.save({ name: "danny" }, function () {
    collection.find().toArray(function (err, results) {
        // results contains the array of docs

        // Now you can close the connection.
        db.close();
    });
});

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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