NodeJS连接MongoDB数据库
阅读原文时间:2023年07月09日阅读:2

NodeJS连接MongoDB数据库

// 引入mongoose第三方模块
const mongoose = require('mongoose');
// 连接数据库
// 第一个要写数据库的地址及其名字
// 还有, 这是一个独立的模块, 必须到另一个js中引入才能看到效果!
// mongoose.connect('mongodb://localhost/数据库名字')
mongoose.connect('mongodb://localhost/Test', { useUnifiedTopology: true })
    .then(() => console.log('数据库连接成功'))
    .catch(() => console.log('数据库连接失败!'))

/*
    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.

【DeprecationWarning:当前URL字符串
解析器已弃用,并将在以后的版本中删除。 要使用新的解析器,请将选项{useNewUrlParser:true}传递给MongoClient.connect。】
*/

require('./data/connect')

最后,在当前的工作目录中输入

nodemon .\app.js

当然以上的命令我是默认你安装了nodemon这个命令行工具的哈!

如果你没有安装, 那么也很简单, 你直接在当前的工作目录输入

node app.js

也可以!

可以看到我们的数据库就连接成功了!

手机扫一扫

移动阅读更方便

阿里云服务器
腾讯云服务器
七牛云服务器

你可能感兴趣的文章