数据库连接
当我们使用之前需要启动 MongoDB :
- 在命令行工具中运行
net start mongoDB
即可启动 MonggoDB ,否则 MongoDB 将无法连接 - 在命令行工具中运行
net stop mongoDB
即可关闭 MonggoDB
使用 mongoose 提供的 connect()
方法即可连接数据库
const mongoose = require('mongoose');
/*
* mongodb:// mongodb 协议
* localhost 本机
* playground 数据库名字
*/
mongoose.connect('mongodb://localhost/playground')
.then(() => console.log('数据库连接成功'))
.catch(err => console,log('数据库连接失败',err));
在 MongoDB 中不需要显式创建数据库,如果正在使用的数据库不存在,MongoDB 会自动创建