node如何连接mongodb数据库

本文提供了一种解决在使用MongoDB时遇到的接口废弃警告的方法。通过在连接字符串中添加useNewUrlParser和useUnifiedTopology选项,可以避免警告并确保代码兼容未来的MongoDB版本。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

解决这两接口废弃的代码在下方,cv即可运行
(node:11064) DeprecationWarning: current URL string parser is deprecated, and will be removed in a future version. To use the new parser, pass option { useNewUrlParser: true } to MongoClient.connect.
(node:11064) 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.

首先我们新建文件夹test
在当前文件夹下打开命令行窗口

依次输入以下代码

npm init

enter

npm install express mongodb --save

enter
不要以为我们的工作已经做完了

你还要开机啊

mongod --dbpath 数据库路径

enter

现在我们依赖的包已经装好了
接下来在我们新建的文件夹下面新建aap.js文件
复制以下代码运行
这里的代码是经过修改的,官网上的代码使用过程中会报两个接口即将废弃的错误
直接运行可以看到已经连接到数据库上了,并且不会报错

var express = require("express");
var app = express();
const MongoClient = require('mongodb').MongoClient;
const assert = require('assert');

// Connection URL
const url = 'mongodb://localhost:27017/haha';
MongoClient.connect(url, {useNewUrlParser:true ,useUnifiedTopology: true},function (err,db) {
    assert.equal(null,err);
    console.log("Connected correctly to Server");
    db.close();
})

app.get("/",function(req,res){
    res.send("Hello");
})
app.listen(3000);
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值