0

I'm trying to wrap various MongoDB methods in a Promise wrapper for a Node.js server but I'm getting a

TypeError: Promise is not a constructor

All the code inside the new Promise constructor wrapper works just fine on its own but I need it inside an asynchronous Promise in order to call it from another place.

const MongoClient = require("mongodb").MongoClient;
const Promise = require("promise");
const mongoURL = "...";

function checkURL (domain, path) {
return new Promise(function (resolve, reject) {
    const client = new MongoClient(mongoURL, { useNewUrlParser: true });

    client.connect()
    .then(db => {
        const collection = client.db("websites").collection("cool_websites");
        return collection.find({domain: domain, path: path}).toArray();
    })
    .then(result => {
        resolve(result);
        client.close();
    })
})
}

console.log(checkURL("www.stackoverflow.com", "/"));

I expect a console.log of

[ { _id: 123abc,
    domain: 'www.stackoverflow.com',
    path: '/questions/',
    cool_website: true } ] 

but in the terminal, I just recieve:

TypeError: Promise is not a constructor
Quoc Tran
  • 45
  • 5
  • Possible duplicate of [How to use MongoDB with promises in Node.js?](https://stackoverflow.com/questions/37911838/how-to-use-mongodb-with-promises-in-node-js) – Randy Casburn May 25 '19 at 20:00
  • 2
    What is `require("promise");` and why do you need it ? – Titus May 25 '19 at 20:00
  • Which version of Node.js are you using? – Dez May 25 '19 at 20:12
  • I'm using Node v10.15.3 but @Titus solved my problem. I was adapting a tutorial on Guru99 and they needed that package to use promises, but just deleting that line allowed everything to work. Sorry for inconvenience and thanks! – Quoc Tran May 25 '19 at 20:30
  • Avoid the [`Promise` constructor antipattern](https://stackoverflow.com/q/23803743/1048572?What-is-the-promise-construction-antipattern-and-how-to-avoid-it)! – Bergi May 25 '19 at 21:26

2 Answers2

0

@Titus answered my question. I was adapting a tutorial on Guru99 and they needed that package to use promises, but just deleting that line allowed everything to work. Thanks!

Quoc Tran
  • 45
  • 5
0

You don't need to require("promise"), it doesn't make any sense. It's probably failing because of that.

Also, your test should be:

checkURL("www.stackoverflow.com", "/")
  .then(result => {
    console.log(result);
  });

Because checkURL is a promise now.

SylvainAr
  • 154
  • 5
  • Thanks! I was confused because I was adapting it from an example [on Guru99.com](https://www.guru99.com/node-js-promise-generator-event.html). I wonder if that package was required in the older version of Node.js that they were using because it wasn't native in JS/Node yet? – Quoc Tran May 26 '19 at 21:16