1. 前言
现在都少不了模块 封装
2. mongodb封装
mgdb.js
const mongoose = require("mongoose"); let db = mongoose.connect("mongodb://127.0.0.1:27017/yzs", { useNewUrlParser: true, useUnifiedTopology: true }); // 挪到外面 let mySchema = new mongoose.Schema({ name: { type: String, default: "无名" }, age: { type: Number, min: 18, default: 20 }, sex: { type: String, default: "未知" } }); const MyModel = mongoose.model("Student", mySchema); module.exports = { model:MyModel, openSuccess:function(fn){ mongoose.connection.on("open", fn); } }
3.server.js
let express = require("express"); let mongo = require("./mgdb"); let app = express(); mongo.openSuccess(function(){ console.log("数据库链接成功"); app.get("/allStudents",function(req,res){ // 查询所有 注意 这个2个回调的参数不要写一样 mongo.model.find(function(err,result){ if(!err){ res.json(result); }else{ res.json({code:534,msg:"没有查询到数据"}); } }); }); }); app.listen(8899,function(){ console.log("服务器已打开") });
4. 小练习
// 懂得都懂,不懂的慢慢了解 let reqUrl = "这里用的是那个是 140条新闻地址"; let express = require("express"); let app = express();//搭建服务器 //静态文件读取的中间件 -- 内置中间件 app.use(express.static(__dirname +"/public")); let http = require("http"); let mongoose = require("mongoose"); mongoose.connect('mongodb://localhost:27017/easy', { useNewUrlParser: true, useUnifiedTopology: true }); mongoose.connection.on("open",function () { console.log("数据库wangyi链接成功"); const mySchema = new mongoose.Schema({ id:{type:String}, title:{type:String}, imgUrl:{type:String}, content:{type:String} }); const MyModel = mongoose.model("news",mySchema); //新闻数据请求 app.get("/wangyiinfo",function (req,res) { //利用http模块,get请求 -- 没有同源策略的影响 //转发 http.get(reqUrl,function (resObj) { let allData = ""; resObj.on("data",function (chunk) { allData += chunk; }); resObj.on("end",function () { //查询数据库 MyModel.find({},{_id:0,id:1},{},function (err,result) { if (err){ return console.error(err); } console.log(result);//查询到的所有数据---只要了id let idArr = [];//存储所有已收藏数据的id for (let i = 0;i < result.length;i++){ idArr.push(result[i].id); } console.log(idArr); //返回数据给前端 res.json({wangyiData:allData,idData:idArr}); }); }); }); }); //收藏页的数据请求 app.get("/collection",function (req,res) { //查询所有数据库中news集合中的数据 MyModel.find(function (err,result) { if(!err){//查询到了 res.json(result); }else { res.json(result);//空 } }); }); //点击收藏按钮的数据请求 app.get("/addCollect",function (req,res) { //获取前端传递过来的数据 // req.query.id1; //插入数据 MyModel.create({ id:req.query.id1, title:req.query.title1, content: req.query.content1, imgUrl: req.query.imgUrl1 },function (err,result) { if(!err){//插入数据成功 res.json({msg:1}); }else { res.json({msg:0}); } }); }); //点击已收藏按钮 -- 删除该条数据 app.get("/deleteCollect",function (req,res) { //删除 MyModel.deleteOne({id:req.query.id1},function (err,result) { if(!err){ res.json({msg:1});//删除数据库中该条数据成功 }else { res.json({msg:0}); } }); }); }); app.listen(8675,function () { console.log("8675启动成功"); });