MongoDB Node.js "Callbacks are deprecated"的问题



你好,我有MongoDB代码的问题,它使一些方法像这样(下图):输入图片描述

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

当我试着读错误时,它说:

MongoClient(方法)。connect(url: string, callback: callback): void(+3重载)@deprecated -回调已被弃用,并将在下一个主要版本中删除。关于迁移帮助,请参阅mongodb-legacy

蒙古包的签名'(url: string, callback: callback): void'。已弃用Connect。ts(6387)mongodb.d。ts(4733,9):声明在这里被标记为deprecated。无快速修复

我试着重新安装它,或者安装旧版本,仍然一样,我做连接一样的文档

尝试添加(url,{useUnifiedTopology: true},但仍然相同

有人知道有什么问题吗?

尝试版本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();
});
});

如果你还是有同样的错误,请告诉我。

步骤1:将当前版本替换为以下内容:

npm install mongodb-legacy

步骤2:在你的项目中要求

const mongoClient = require('mongodb-legacy').MongoClient

最新更新