1."zhijie.js"文件
//通过find直接查询的表
var mongoose = require('mongoose')
var labelSchema = mongoose.Schema({
blogid: {type: mongoose.Schema.Types.ObjectId, ref: 'blog'},//这里即为子表的外键,关联主表。 ref后的blog代表的是关联表为blog的Model。
label: {type: String} //标签名
});
//创建model,第一个参数为自身model,第三个参数是实际表名
let db=mongoose;
var labelModel = db.model("label", labelSchema, "label");
module.exports=labelModel;
2.user.js文件
var mongoose = require('mongoose')
var blogSchema =mongoose.Schema({
title: {type: String},
click: {type: Number}
})
let db=mongoose;
var blogModel = db.model("blog", blogSchema, "blog");
module.exports=blogModel;
3.connect.js文件,用来连接数据库
var mongoose=require('mongoose');
mongoose.connect('mongodb://localhost:27017/test',{useNewUrlParser:true});
var db=mongoose.connection;
db.on("err",function(error){console.log(error);});
db.on("open",function(){
console.log("sucess");
});
db.on("disconnected",function(){console.log("断开连接");});
module.exports=db;
4.main.js文件---执行文件
const express = require('express');
const bodyParser = require('body-parser');
var server = express();
server.all("*",function(req,res,next){
res.header("Access-Control-Allow-Origin", "*");
res.header("Access-Control-Allow-Headers", "X-Requested-With");
res.header("Access-Control-Allow-Methods", "PUT,POST,GET,DELETE,OPTIONS");
res.header("X-Powered-By", ' 3.2.1')
res.header("Content-Type", "application/json;charset=utf-8");
next();
});
server.use(bodyParser.json());
server.use(bodyParser.urlencoded({extended: false}));
let db=require("./connect.js");//链接并打开data数据库
let zhijie=require("./post.js");
let user=require("./user.js");
server.post("/",function(req,res){
user.insertMany({title:req.body.title,click:req.body.click},(err,doc)=>{
//insertMany后的doc是数组,即使只有一个
zhijie.insertMany({blogid:doc[0]._id,label:req.body.label},(err1,doc1)=>{
})
})
})
server.post("/search",function(req,res){
zhijie.find({}).populate('blogid').exec(function(err,docs){
console.log(docs);
})
})
server.listen(8080);