pm2 reload all(刷新)
一、安装monoose(链接数据库)
二、创建models(mongoose创建model实体,通过实体和mongodb关联数据库)
models/goods.js
var mongoose=require('mongoose')
var Schema=mongoose.Schema;
var productSchema=new Schema({
"productId" :String,
"productName":String,
"salePrice":Number,
"productImage": String,
"productUrl": String
})
module.exports=mongoose.model('Good',productSchema);
三、创建路由(通过路由查看接口,通过路由调model实体,通过model的api查询数据库)
routes/goods.js
/*二级路由*/
var express = require('express');
var router = express.Router();
var mongoose=require('mongoose');
var Goods=require('../models/goods');
//链接数据库
mongoose.connect('mongodb://127.0.0.1:27017/dumall');
//监听数据库是否链接成功
mongoose.connection.on("connected",function(){
console.log('mongoose connect success');
})
mongoose.connection.on("error",function(){
console.log('mongoose connect success');
})
mongoose.connection.on("disconnected",function(){
console.log('mongoose connect success');
})
router.get("/",function(req,res,next){
Goods.find({},function(err,doc){
if(err){
res.json({
status:'1',
meg:err.message
})
}else{
res.json({
status:'0',
msg:'',
result:{
count:doc.length,
list:doc
}
})
}
})
})
module.exports=router;
配置路由app.js
var goods = require('./routes/goods');
app.use('/goods', goods);
四、基于mongoose实现商品列表查询功能
访问http://localhost:3000/goods即可查看数据库返回结果