node.js - 使用 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);
所需关系图:
解决方案
推荐阅读
- javascript - 在 base64 中发送更大的图像时,Nodemailer 崩溃
- git - 如何列出所有分支中每个作者的最新提交?
- vba - IBM MAXIMO:如何使用 REST API 从 PR 创建 PO
- java - 无法运行程序“AdoptOpenJDK\jdk-8.0.232.09-hotspot\jre\bin\java.exe”:CreateProcess 错误=206,文件名或扩展名太长
- node.js - RDS 管理控制台中显示的 sequelize 和连接中最大连接池大小的差异
- javascript - ES6中没有变量声明的对象解构赋值
- java - java.lang.NullPointerException:'void android.widget.Button.setOnClickListener(android.view.View$OnClickListener)' 在空对象引用上
- python - 将矩阵表中的数据带到按日期分组的行中
- postgresql - 在 PostgreSql 中返回带有存储过程的表?
- spring - 执行器检查活页夹失败