学习内容:
使用mongodb存储数据,用node语言编写后端
学习产出:
【下载mongoose依赖包】
npm install mongoose
【创建一个js文件】
keys.js
文件写入路径配置(模块入口)
module.exports = { mongoURI: "mongodb://localhost/playground", secretOrkey: "secret", };
mongoURI是连接mongodb数据库的路径,路径中的数据库(此代码的数据库名为playground)不存在则会创建该数据库。
【server.js入口文件】
导入mongoose
const mongoose=require("mongoose");
引入keys.js
const db=require("./config/keys").mongoURI;
连接数据库
mongoose .connect(db) .then(() => console.log("数据库连接成功")) .catch((err) => console.log(err, "数据库连接失败"));
【搭建路由】
新建文件夹routes
在routes中新建文件 users.js
1.需要导入express、router
const express = require("express