当前位置: 首页 > news >正文

【mongoose8.x】mongoose8.x入门教程(二):express中mongoose的链接

mongoose是nodejs的框架,所以我们需要在nodejs的后端框架中才能使用,比如express,koa等。

项目准备

新建一个express(或koa)的项目
在这里插入图片描述

修改相关的默认文件配置,启动项目
在这里插入图片描述
看到这样的界面,就说明我们项目搭建成功了。

下面,我们来引入mongoose的操作

根据官网的文档demo进行操作即可:https://mongoosejs.com/docs/index.html
在这里插入图片描述

mongoose的链接

// getting-started.js
const mongoose = require("mongoose");
mongoose.connect("mongodb://127.0.0.1:27017/vueshopapp");
const db = mongoose.connection;
db.on("error", console.error.bind(console, "connection error:"));
db.once("open", function () {// we're connected!console.log("Connected successfully");
});module.exports = mongoose;

创建一个collection

const mongoose = require("..");
const { Schema } = mongoose;const GoodsSchema = new Schema({productId: { type: String, required: true },productName: { type: String, required: true },salePrice: { type: Number, required: true },productImage: { type: String, required: true },productUrl: String,
});const Goods = mongoose.model("Good", GoodsSchema);module.exports = Goods;

collections的使用

  • 查询商品列表
/* GET Goods page. */
router.get("/list", async function (req, res, next) {try {const goods = await Goods.find({});res.json(Result.success(goods));} catch (err) {handleError(err);res.json(Result.error("查询失败!"));}
});

注意这里的语法格式,mongoose8.x里面的find不支持回调函数了,需要使用async/await来写

查询数据效果
在这里插入图片描述
当然也可以在apifox或其他的接口调试工具中使用
在这里插入图片描述

封装下返回数据

一般,我们在做项目的时候,后端返回给前端的数据格式是一致的,所以有必要封装下返回格式

class Result {static success(data = "") {return {code: 10000,success: true,data: data,};}static error() {return {code: 10001,success: false,data: null,};}
}module.exports = Result;

可以自行扩展上面的Result。

新增一个商品

// 添加商品
router.post("/add", async function (req, res, next) {try {const goods = new Goods(req.body);console.log("🚀 ~ :25 ~ goods:", goods);await goods.save();res.json(Result.success("添加成功!"));} catch (err) {handleError(err);res.json(Result.error("添加失败!"));}
});

一般是post请求,这下我们必须在apifox等工具中进行调试了
在这里插入图片描述
后端日志:
在这里插入图片描述
可以从页面中查看到,新数据被新增进去了
在这里插入图片描述
在这里插入图片描述
在compass中,刷新数据后就看到了刚才添加的数据,也就表明数据持久化完成了。

相关文章:

  • 23种设计模式--简单工厂模式理解版
  • Flutter中FutureBuilder和StreamBuilder
  • Haproxy搭建web集群
  • 使用 Prometheus 访问 TDengine ---
  • 计算机导论期末快速复习指南
  • 第一章 SQL编程系列-数据库介绍与安装
  • Unity UI 核心类解析之Graphic
  • crawl4ai 框架的入门讲解和实战指南——基于Python的智能爬虫框架,集成AI(如NLP/OCR)实现自动化数据采集与处理
  • DDS 问题排查
  • 基于自然语言处理的智能问答系统(模型训练+部署测试)
  • 【图片识别改名】批量识别图片中的文字对图片进行改名,识别文字对图片重新命名的操作步骤和注意事项
  • python学智能算法(十四)|机器学习朴素贝叶斯方法进阶-CountVectorizer文本处理简单测试
  • CD45.【C++ Dev】STL库的list的使用
  • 前端基础知识CSS系列 - 14(CSS提高性能的方法)
  • windows,java后端开发常用软件的下载,使用配置
  • Spring MVC参数绑定终极手册:单多参对象集合JSON文件上传精讲
  • Python 开发环境全栈隔离架构:从 Anaconda 到 PyCharm 的四级防护体系
  • mcp-server-chart Quickstart
  • Android中Native向System Service进行Binder通信的示例
  • Tensorflow推理时遇见PTX错误,安装CUDA及CuDNN, 解决问题!
  • 温州 网站建设/平台seo
  • 域名备案与网站备案的区别/威海网站制作
  • 尤溪建设局网站/win7运行速度提高90%
  • 免费装修效果图网站/seo查询排名软件
  • 无锡网站优化推广/seo搜索引擎优化是什么
  • 用php做电子商务网站/今日国内新闻最新消息