Home > Software engineering >  MongoDB Node.js issue with "Callbacks are deprecated"
MongoDB Node.js issue with "Callbacks are deprecated"

Time:12-22

Hello I have issue with MongoDB code, it make some methods like this (image below): enter image description here

`

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

MongoClient.connect(url, { useUnifiedTopology: true }, function (err, db) {
  if (err) throw err;
  var dbo = db.db("mydb");
  var mysort = { name: 1 };
  dbo.collection("customers").find().sort(mysort).toArray(function (err, result) {
    if (err) throw err;
    console.log(result);
    db.close();
  });
});

`

and when I try read error, it say:

(method) MongoClient.connect(url: string, callback: Callback): void ( 3 overloads) @deprecated — Callbacks are deprecated and will be removed in the next major version. See mongodb-legacy for migration assistance

The signature '(url: string, callback: Callback): void' of 'MongoClient.connect' is deprecated.ts(6387) mongodb.d.ts(4733, 9): The declaration was marked as deprecated here. No quick fixes available

I tried reinstall it, or install older version and still same, I do connection same like in documentation.

Tried add (url,{ useUnifiedTopology: true }, and still same

Someone know what can be issue?

CodePudding user response:

Try version 4.0.0

const MongoClient = require('mongodb').MongoClient;

// Connect to the MongoDB server
MongoClient.connect('mongodb://localhost:27017/', function(err, client) {
  if (err) throw err;

  // Get the sample database
  const db = client.db('sample');

  // Get the collection
  const collection = db.collection('test');

  // Insert a document
  collection.insertOne({ name: 'John', age: 30 }, function(err, result) {
    if (err) throw err;

    console.log(result);

    // Close the connection
    client.close();
  });
});

Let me know if you still have the same error .

  • Related