1

I keep getting promise pending.

var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {
    if (err) throw err;

    var dbo = db.db("mydb");
    var gr = dbo.collection("collectionname").distinct("name");

    // var everyrecord = dbo.collection("collectionname").find({}).toArray();

    console.log(gr);

    db.close();
});

3 Answers 3

1

If you make the function async, you can just await the result:

MongoClient.connect(url, { useNewUrlParser: true } , async function(err, db) {
    // ...

    var gr = await dbo.collection("collectionname").distinct("name");
    console.log(gr);

    // ...
});
Sign up to request clarification or add additional context in comments.

1 Comment

@f.pythonlover Any reason the other (non working) answer is marked as solution?
0
var MongoClient = require('mongodb').MongoClient;
var url = "mongodb://localhost:27017/";

MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {

if (err) throw err;

var dbo = db.db("mydb");

 var gr = dbo.collection("collectionname").distinct("name");
 gr = gr.toArray();

// var everyrecord = dbo.collection("collectionname").find({}).toArray();

  console.log(gr);

  db.close();
});

1 Comment

There is no toArray method on Promises. Check out stackoverflow.com/questions/20858299/…
0

You can achive this by using .toArray(),

    var MongoClient = require('mongodb').MongoClient;
    var url = "mongodb://localhost:27017/mydb";

    MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) {

      if (err) throw err;

      db.collection("collectionname").distinct("name").toArray(function (error, response) {
         console.log(error);
         console.log(response);
      });
    });

3 Comments

MongoClient.connect(url, { useNewUrlParser: true } , function(err, db) { if (err) throw err; var dbo = db.db("mydb"); dbo.collection("collectionname").distinct("name").toArray(function (error, response) { console.log(error); console.log(response); }); }); this didn t work? what am i missing?
it says that toarray is not a function
You're not missing anything. There is no toArray method for promises. Have a look at my async/await suggestion - assuming your node version supports it.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.