首页 > 解决方案 > 使用 refpath 为 Express Nodejs API 构建 Mongoose 模型

问题描述

我是使用 mongoose 和 express 构建 rest api 的新手,并且对如何在我的模型文件上正确使用 refPath 并允许一系列项目有疑问。

下面我已经包含了一个模型的代码(迄今为止构建的),如果我接近正确构建它,我会喜欢任何输入。

我还将包含一个屏幕截图,直观地描述我正在尝试创建的关系。

在这里回答问题的人是上帝,我感谢这个社区多年来给我的所有帮助!

const mongoose = require("mongoose");
const slugify = require("slugify");

const AlertSchema = new mongoose.Schema({
  parentId: {
    type: mongoose.Schema.ObjectId,
    required: true,
    refPath: "parentModel",
  },
  parentModel: {
    type: String,
    required: true,
    enum: ["orgs", "clients"],
  },
  status: { type: String, default: "no-status" },
  departments: [{ type: mongoose.Schema.Types.ObjectId, ref: "orgs" }],
  createdAt: { type: Date, default: Date.now },
  createdByType: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
  createdById: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
  groups: [{ type: String, default: "unGrouped" }],
  stage: [{ type: mongoose.Schema.Types.ObjectId, ref: "stages" }],
  children: { type: String },
  resource: {
    type: String,
    match: [
      /https?:\/\/(www\.)?[-a-zA-Z0-9@:%._\+~#=]{1,256}\.[a-zA-Z0-9()]{1,6}\b([-a-zA-Z0-9()@:%_\+.~#?&//=]*)/,
      "Please use a valid URL with HTTP or HTTPS",
    ],
  },
  notes: [{ type: mongoose.Schema.Types.ObjectId, ref: "notes" }],
  comments: [{ type: mongoose.Schema.Types.ObjectId, ref: "comments" }],
  priority: { type: String },
  assignedTo: [{ type: mongoose.Schema.Types.ObjectId, ref: "users" }],
  title: {
    type: String,
    required: [true, "Please add a title"],
    maxlength: [50, "Title cannot be more than 50 characters"],
  },
  message: {
    type: String,
    required: [true, "Please add a message"],
    maxlength: [500, "Message cannot be more than 500 characters"],
  },
  slug: String,
});

//create alert slug from the title
AlertSchema.pre("save", function (next) {
  console.log("Slugify Ran", this.name);
  this.slug = slugify(this.title, { lower: true });
  next();
});



module.exports = mongoose.model("Testalert", AlertSchema);

所需关系图:

在此处输入图像描述

标签: node.jsmongodbrestexpressmongoose

解决方案


推荐阅读