A
A
Alexey2020-07-06 23:04:47
MongoDB
Alexey, 2020-07-06 23:04:47

How to fix error in nodejs working with mongodb?

const mongo = require('mongodb').MongoClient
const url = 'mongodb://localhost:27017';

mongo.connect(url, { useNewUrlParser: true }, (err, client) => {
  if (err) {
    console.log('Connection error: ', err)
    throw err
  }

  console.log('Connected')

  const db = client.db('pageLinks');
  const allLinks = db.collection('allLinks');

allLinks.find({subcategory: 'subcategory2'}).toArray(function(err, results){     
    console.log(results);
  });

  client.close();
})


Good evening)
Help me understand. I study the work of node with the database. With this code, an error flies, but everything works, although I think not for a long time
spoiler
(node:8112) DeprecationWarning: current Server Discovery and Monitoring engine is deprecated, and will be removed in a future version. To use the new Server Discover and Monitoring engine, pass option { useUnifiedTopology: true } to the MongoClient constructor.
(Use `node --trace-deprecation ...` to show where the warning was created)


If you change the line to
mongo.connect(url, { useNewUrlParser: true, useUnifiedTopology: true }, (err, client) => {...})

then the error disappears in the console, but the result of the code
allLinks.find({subcategory: 'subcategory2'}).toArray(function(err, results){     
    console.log(results);
  });

will be undefined - why? And how to fix it?

Answer the question

In order to leave comments, you need to log in

1 answer(s)
A
Alexey, 2020-07-07
@Evelate

It seems that the error with undefined has been fixed. client.close() was faster than allLinks.find() completed.
I ended up changing the line like this:

allLinks.find({subcategory: 'subcategory2'}).toArray(function(err, results){     
    console.log(results);
    client.close();
  });

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question