mongoose连接详情参考官网
在项目中新建db文件夹
connect.js连接mongo:
const mongoose=require('mongoose'); mongoose.connect("mongodb://localhost/27017",{ useNewUrlParser: true, useUnifiedTopology: true}); // 端口号以自己启动的mongod为准 var db=mongoose.connection; db.on('error',console.error.bind(console,'connection error')); db.once('open', function() { console.log('db start'); })
model文件下为您要创建的数据表,格式如:
const mongoose=require('mongoose'); var userSchema=new mongoose.Schema({ us:{type:String,required:true}, ps:{type:String,required:true}, age:Number, sex:{type:Number,default:0} }); var User=mongoose.model('user',userSchema); module.exports=User;
数据建好后,将数据库连接到服务文件中 如:server.js
const db=require('./db/connect');
路由中引入数据表如在router>foodRoute.js 中引入
const foodModel=require('../db/model/foodModel');