简体   繁体   中英

MongoDB connection with nodejs returns promise <pending>

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:

  1. connect to mongoDB
  2. before inserting a document, I want to check if there is already an existing name. If the name is already taken return an error
  3. insert the document.

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!

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. ie

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM