首页 > 解决方案 > Mongoose - 引用另一个表中的字段

问题描述

我有两个表:Post并且User我想在 Post 表中引用用户名。

我可以引用 ID,但我还需要名称。

用户型号:

const userSchema = new mongoose.Schema({
  username: {
    type: String,
    required: true,
  },
  email: {
    type: String,
    required: true,
  },
  password: {
    type: String,
    required: true,
  },
})
module.exports = mongoose.model("User", userSchema)

岗位型号:

const { ObjectId } = mongoose.Schema.Types
const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: true,
  },
  author: {
    type: ObjectId,
    ref: "User",
  },
})
module.exports = mongoose.model("Post", postSchema)

他们在文档中说:

注意:ObjectId、Number、String 和 Buffer 可用作 refs。但是,除非您是高级用户并且有充分的理由这样做,否则您应该使用 ObjectId。

但是,我找不到有关如何执行此操作的示例。

标签: node.jsmongodbmongoose

解决方案


推荐阅读