LChampo
LChampo

Reputation: 77

Mongo - How to check an existing field before insert or update a given document

Im using Mongodb in NodeJs and I would like to know if it exists a right way to check an existing field before insert and update a given document.

Let's assume i have a collection named 'gates' that i want to insert new document or to update an existing document into. So, i tried this

let exist = db.collection('gates').find({_id: {$eq: somevalue}}).toArray(
    (err, res) => {
        if(err) throw err;

        return res.length > 0;  
    }
);

Here is my problem, my variable exist has an undefined value and not a boolean value. How can i fix it ?

Upvotes: 1

Views: 776

Answers (1)

rodrigoap
rodrigoap

Reputation: 7480

You should use a Promise because the query is evaluated async.

static countGates(somevalue) {
    return new Promise((resolve, reject) => {
        db.collection('gates').find({_id: {$eq: somevalue}}).toArray(
            (err, res) => {
                if(err) {
                    reject(err);
                }
                resolve(res.length > 0);  
            }
        );
    });
}

Upvotes: 1

Related Questions