Reputation:
Good morning everyone! Few weeks ago I started learning javascript, node.js and mongo, so I am pretty new. Today I want to make a simple task. I want to add a simple document to the mongoDB and to check a conditional. So I want to make this:
I did this:
function addDocument(req, res){
//did some statements to check valid document fields and values
MongoClient.connect(uri, {
useUnifiedTopology: true
}, (err, client) => {
if (err) return console.error(err)
console.log('Connected to Database')
let db = client.db('data');
let serviceCollection = db.collection('services');
let checkName = serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
return result;
})
console.log(checkName);//this doesn't print anything and returns the pending promise
//here I want to put a conditional statement like: if(checkName>0) return res.send("name already exists")
serviceCollection.insertOne(service)
})
return res.send("Done!")
}
If I remove the statement console.log or "if" It works. It adds the document into the DB, but with duplicated "name"s. If I modify the console.log with:
checkName.then(r=>{console.log(r)})
then it prints the number of documents that has the given name. What should I do to handle that with an "if" statement and return the error if it is > 0 ?
The JSON document looks like:
{
"name": "marco",
"field2": "example"
//etc
}
This function is exported to app.js and used in the post method as callback. Thank you very much!
Upvotes: 0
Views: 1000
Reputation: 766
The issue you have is that you are not waiting for the promise to be fulfilled.You can either move the code to once the promise is fulfilled or await it. Have a look at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise. Change the code from
let checkName = serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
return result;
})
To
let checkName = await serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count();
Or wait for the promise to fulfill before using its return value. i.e
serviceCollection.find({
'name': name //this variable is declared as req.body.name and it prints the name from the request
}).count().then(result => {
console.log(result);//this doesn't print anything and returns the pending promise
//here I want to put a conditional statement like: if(checkName>0) return res.send("name already exists")
serviceCollection.insertOne(service)
})
})
Upvotes: 1