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

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

项目准备

新建一个express(或koa)的项目

修改相关的默认文件配置,启动项目

看到这样的界面,就说明我们项目搭建成功了。

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

根据官网的文档demo进行操作即可:https://mongoosejs.com/docs/index.html

mongoose的链接

js 复制代码
// 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

js 复制代码
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的使用

  • 查询商品列表
js 复制代码
/* 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或其他的接口调试工具中使用

封装下返回数据

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

js 复制代码
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。

新增一个商品

js 复制代码
// 添加商品
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中,刷新数据后就看到了刚才添加的数据,也就表明数据持久化完成了。

相关推荐
米码收割机1 天前
SA508-3钢回火焊道焊接温度场数值模拟(模拟图+论文)
spring boot·express·宠物
Pu_Nine_92 天前
Vue3+TS+Express 转 Nuxt4 全栈开发笔记(Drizzle ORM + MySQL)
前端·vue·express·nuxt.js·全栈框架
张人玉6 天前
基于 Vue 3 + ECharts + Express + SQLite 构—— LDA 模型的新闻舆论主题识别与情感分析系统
vue.js·echarts·express
张人玉8 天前
基于 Vue 3 + ECharts + Express + SQLite 的可视化大屏与业务管理系统——YOLOv8 高精度车辆行人检测与计数系统
数据库·vue.js·yolo·sqlite·echarts·express
张人玉10 天前
基于 Vue 3 + ECharts + Express + SQLite 构建的鞋类零售数据分析与毛利预测平台——基于深度学习的鞋类销售数据分析系统
vue.js·sqlite·echarts·express
张人玉13 天前
基于 Vue 3 + ECharts + Express + SQLite 的世界数据可视化大屏系统——世界态势数据可视化大屏
vue.js·echarts·express
张人玉15 天前
基于 Vue3 + ECharts + Express + SQLite 的智慧交通数据可视化系统——郑州交通数据可视化大屏
sqlite·echarts·express
张人玉17 天前
基于 Vue2 + ECharts + Express + SQLite 的南阳市专题数据可视化系统
sqlite·echarts·express
2301_7681034920 天前
HarmonyOS宠物邻里实战第16篇:寄养申请状态机、记录时间线与回归测试
mongodb·集成测试·express·harmonyos·状态机
万亿少女的梦1681 个月前
基于Node.js和Express的旅游信息管理平台设计与开发
mysql·node.js·express·系统设计·旅游信息管理