我有一个Comment模型, comments 可以添加到Post或其他Comment.我希望定义一个指向PostComment型号的parentCollection字段,然后定义对象的ID,而不是定义两个可选的parentPostparentComment字段.我是Mongoose/MongoDB的新手.这是可能的吗?这种方法有什么警告吗?

// What I have
const commentSchema = new Schema({
  parentComment: {type: Schema.Types.ObjectId, ref: 'Comment'},
  parentPost: {type: Schema.Types.ObjectId, ref: 'Post'}
})
// What I want
const commentSchema = new Schema({
  parentModel: {}, // Not sure what to put here, String maybe?
  parentID: {type: Schema.Types.ObjectId} // Maybe ref could point to parentModel?
})

我的目标是减少具有许多可能的父类型的模型的字段数量.这在实践中曾经这样做过吗?或者第一种具有多个领域的方法是常见的方法吗?

推荐答案

您可以使用refPath创建动态引用

例如,在您的用例中可以执行如下操作

const postSchema = mongoose.Schema({
    //....
});

const commentSchema = mongoose.Schema({
    parentID: {
      type: mongoose.Schema.Types.ObjectId,
      required: true,
      refPath: 'parentModel'
    },
    parentModel: {
      type: String,
      required: true,
      enum: ['Comment', 'Post']
    },
    //....
});

const Post = mongoose.model('Post', postSchema);
const Comment = mongoose.model('Comment', commentSchema);

Javascript相关问答推荐

Node.JS ws包中是否有Webocket的错误代码列表?

如何使用JavaScript对切换的声音设置音量

JavaScript .Click()函数不起作用

如果没有尾随斜线,托管在收件箱中的React/Vite将无法工作

在HTML中使用脚本变量作为背景图像源

如何访问react路由v6加载器函数中的查询参数/搜索参数

我不知道为什么我的JavaScript没有验证我的表单

使用json文件字符串来enum显示类型字符串无法按照计算的enum成员值的要求分配给类型号

从实时数据库(Firebase)上的子类别读取数据

如何解决chrome—extension代码中的错误,它会实时覆盖google—meet的面部图像?'

google docs boldText直到按行执行应用脚本错误

自定义高图中的x轴标签序列

无法检测卡片重叠状态的问题

如何在 cypress 中使用静态嵌套循环

Reaction Redux&Quot;在派单错误中检测到状态Mutations

TinyMCE 6导致Data:Image对象通过提供的脚本过度上载

当标题被点击时,如何使内容出现在另一个div上?

未捕获的运行时错误:调度程序为空

本地损坏的Java脚本

如何在尚未创建的鼠标悬停事件上访问和着色div?