Reputation: 77
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
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