当前位置:网站首页>node连接mongoose数据库流程
node连接mongoose数据库流程
2022-08-03 16:22:00 【是张鱼小丸子鸭】
目录
创建项目命令
express --view ejs 项目名
进入项目,我们需要npm i 下载配置文件
有时候会出先端口已经被占用的情况,我们可以在bin目录下www文件中修改端口

连接mongoose数据库
我们创建一个新的文件夹,然后在文件夹下创建一个连接mongoose数据库的文件,代码如下
var mongoose=require('mongoose')
mongoose.connect('mongodb://127.0.0.1:27017/reactobj',function(err){
if(!err){
console.log('数据库连接成功');
}
})
module.exports=mongoose接着我们创建一个mongoose表,在表中引入连接数据库的文件,在里面创建表字段
var mongoose=require('./Conn')
var Schema=mongoose.Schema
let CartSchema=new Schema({
name:String,
prize:Number,
phopo:String,
num:Number
})
const CartModel = mongoose.model("cart",CartSchema)
module.exports={CartModel}接着我们在router下的index文件中写我们的增删改查操作,在index文件中引入我们表
var express = require('express');
var router = express.Router();
var {CartModel}=require('../conn/Cart')
/* GET home page. */
// router.get('/', function(req, res, next) {
// res.render('index', { title: 'Express' });
// });
// 购物车添加
router.post('/addCart',async (req,res)=>{
let data=await CartModel.create(req.body)
res.send({code:200,msg:'添加成功'})
})
// 购物车查找
router.get('/getCart',async (req,res)=>{
let data=await CartModel.find({}).exec()
res.send({code:200,msg:'成功',data})
})
module.exports = router;通过res.send发送后端数据,是一个对象格式
配置跨域
我们在入口文件中配置跨域,首先需要下载跨域cors
npm i cors -g然后进行配置
var cors=require('cors')
app.use(cors())
运行
运行命令:nodemon通过nodemon运行项目后,如果终端显示数据库连接成功,那么说明我们连接数据库成功,接着写我们后端接口即可
边栏推荐
- [QT] Qt project demo: data is displayed on the ui interface, double-click the mouse to display specific information in a pop-up window
- C专家编程 第3章 分析C语言的声明 3.6 typedef int x[10]和#define x int[10]的区别
- 使用.NET简单实现一个Redis的高性能克隆版(一)
- 【There is no tracking information for the current branch. Please specify which branch you want to 】
- B站回应HR称核心用户是Loser;微博回应宕机原因;Go 1.19 正式发布|极客头条
- [Deep Learning] Today's bug (August 2)
- Some optional strategies and usage scenarios for PWA application Service Worker caching
- Spark entry learning-2
- C专家编程 第3章 分析C语言的声明 3.2 声明是如何形成的
- 《社会企业开展应聘文职人员培训规范》团体标准在新华书店上架
猜你喜欢
随机推荐
蒋松廷 荣获第六季完美童模全球总决赛 全球总冠军
参与便有奖,《新程序员》杂志福利来袭!
SQL中对 datetime 类型操作
如何设计大电流九线导电滑环
Small Tools (4) integrated Seata1.5.2 distributed transactions
移动应用出海,你的“网络优化”拖后腿了吗?
[QT] Qt project demo: data is displayed on the ui interface, double-click the mouse to display specific information in a pop-up window
使用 PowerShell 将 Windows 转发事件导入 SQL Server
Interpretation of the 2021 Cost of Data Breach Report
Leetcode76. Minimal Covering Substring
uniapp隐藏导航栏和横屏显示设置
【系统学习编程-编程入门-全民编程 视频教程】
How to start an NFT collection
[Unity Getting Started Plan] Basic Concepts (8) - Tile Map TileMap 01
Windows 事件查看器记录到 MYSQL
C专家编程 第1章 C:穿越时空的迷雾 1.9 阅读ANSI C标准,寻找乐趣和裨益
【翻译】关于扩容一个百万级别用户系统的六个课程
纯纯粹粹纯纯粹粹
leetcode-693.交替位二进制数
Yuan xiaolin: Volvo focus on travel security, and put it perfectly









