Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Check if a document exists in mongoose (Node.js)

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);
            }
        }
    })
}
like image 932
p0lAris Avatar asked Sep 14 '25 17:09

p0lAris


2 Answers

You have to read about javascript scope. Anyway try the following code,

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]);
}

Note: Since It includes some db operation, I am not tested.

like image 145
HILARUDEEN S ALLAUDEEN Avatar answered Sep 16 '25 08:09

HILARUDEEN S ALLAUDEEN


I found it simpler this way.

let docExists = await Model.exists({key: value});
console.log(docExists);

Otherwise, if you use it inside a function, make sure the function is async.

let docHandler = async () => {
   let docExists = await Model.exists({key: value});
   console.log(docExists);
};
like image 35
Mehedi Avatar answered Sep 16 '25 07:09

Mehedi