MongoDB noob question: Checking if document already exists

Viewed 40

By searching on internet I figured out that this is the way to check if a document already exists.

function addSpam(spam){
    MongoClient.connect(uri, function(err, db) {
        if (err) throw err;
        const dbo = db.db("database0");
        const query = {link: spam};
        const document = dbo.collection("spams").find(query).limit(1);
        console.log(document);
        db.close();
        });       
}

Output log

Now my issue is that a cursor is returned (as you can see in the output log), I would like to have a bool returned, thanks in advance. (whether the document was found or not)

1 Answers

I figured it out:

function addSpam(spam){
MongoClient.connect(uri, function(err, db) {
    if (err) throw err;
    const dbo = db.db("database0");
    const query = {"link": spam}; //spam is item to find inside a document and link is the field name of the document
    dbo.collection("spams").find(query).toArray(function(err, result) {
        if (err) throw err;
        const docFound = result.length>0;
        console.log(docFound);
        db.close();
      });
    })}; 

There is probably a better method than this but now I got it working fine.

Related