3

I have seen a number of ways of finding documents in mongoDB such that there is no performance hit, i.e. you don't really retrieve the document; instead you just retrieve a count of 1 or 0 if the document exists or not.

In mongoDB, one can probably do:

db.<collection>.find(...).limit(1).size()

In mongoose, you either have callbacks or not. But in both cases, you are retrieving the entries rather than checking the count. I simply want a way to check if a document exists in mongoose — I don't want the document per se.

EDIT: Now fiddling with the async API, I have the following code:

for (var i = 0; i < deamons.length; i++){
    var deamon = deamons[i]; // get the deamon from the parsed XML source
    deamon = createDeamonDocument(deamon); // create a PSDeamon type document
    PSDeamon.count({deamonId: deamon.deamonId}, function(error, count){ // check if the document exists
        if (!error){
            if (count == 0){
                console.log('saving ' + deamon.deamonName);
                deamon.save() // save
            }else{
                console.log('found ' + deamon.leagueName);
            }
        }
    })
}
4

3 に答える 3

4

JavaScriptスコープについて読む必要があります。とにかく、次のコードを試してください。

for (var i = 0; i < deamons.length; i++) {
    (function(d) {
        var deamon = d
        // create a PSDeamon type document
        PSDeamon.count({
            deamonId : deamon.deamonId
        }, function(error, count) {// check if the document exists
            if (!error) {
                if (count == 0) {
                    console.log('saving ' + deamon.deamonName);
                    // get the deamon from the parsed XML source
                    deamon = createDeamonDocument(deamon);
                    deamon.save() // save
                } else {
                    console.log('found ' + deamon.leagueName);
                }
            }
        })
    })(deamons[i]);
}

注: いくつかの db 操作が含まれているため、テストされていません。

于 2013-10-29T21:12:31.377 に答える
1

countを使用できますが、エントリは取得されません。これは、次のような mongoDB のカウント操作に依存しています。

Counts the number of documents in a collection. 
Returns a document that contains this count and as well as the command status. 
于 2013-10-29T20:05:14.540 に答える