【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中,刷新数据后就看到了刚才添加的数据,也就表明数据持久化完成了。

相关推荐
蓝乐2 天前
Express 知识点总结
node.js·express
小粉粉hhh3 天前
Node.js(四)—— Express
node.js·express
Hello:CodeWorld5 天前
PCIe(PCI Express)技术详解:架构、演进与实践
linux·嵌入式硬件·express
ZengLiangYi12 天前
用 ChatCrystal 学 Fastify:从零搭建 REST API
restful·express
zyl8372115 天前
Express快速上手
https·node.js·express
vim怎么退出16 天前
排查 WebSocket "Invalid frame header" 的一次复盘
websocket·node.js·express
学习使我快乐0118 天前
Express 学习
学习·node.js·express
Json____25 天前
node-电商商城平台实战项目(管理端+用户端)
node·vue2·express·element-ui·电商商城
星光开发者1 个月前
基于springboot电动汽车租赁管理系统-计算机毕设 附源码 11217
javascript·spring boot·mysql·django·php·html5·express
一袋米扛几楼981 个月前
【报错问题】解决 Vercel 部署报错:Express 类型失效与 TypeScript 2349/2339/2769 错误排查
ubuntu·typescript·express