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

相关推荐
十月ooOO8 小时前
Express.js 在 ts 模式下运行 npm run dev 的时候无法找到引入项的原因
javascript·npm·express
水冗水孚3 天前
面试官:你是前端你了解oss吗?我反手写了一个react+express+minio实现oss文件存储功能
react.js·node.js·express
snpgroupcn5 天前
泰国零售巨头 CJ Express 借助 SAP 内存数据库实现高效数据管理
数据库·express·零售
水冗水孚5 天前
使用nodejs的express框架实现大文件上传的功能,附完整前后端github代码
javascript·node.js·express
程序猿小D7 天前
第29节 Node.js Query Strings
node.js·vim·express
程序猿小D8 天前
第24节 Node.js 连接 MongoDB
数据库·mongodb·npm·node.js·编辑器·vim·express
接着奏乐接着舞10 天前
nodejs express 打包部署
express
掉头发类型的选手12 天前
Node.js: express 使用 Open SSL
express
不写八个16 天前
Express教程【006】:使用Express写接口
express