【问题标题】:Mongoose schema with field of an array of other schemas具有其他模式数组字段的猫鼬模式
【发布时间】:2021-04-07 04:03:54
【问题描述】:

首先,我是一名初学者,目前我正在研究社交媒体博客类型。 现在,我有了 userSchemapostSchema 模型:

用户模型

const userSchema = new mongoose.Schema({
  name: {
    type: String,
    required: [true, 'Please insert your name'],
  },
  email: {
    type: String,
    required: [true, 'Please insert your email'],
    unique: true,
    lowercase: true, //transform into lowercase / not validator
    validate: [validator.isEmail, 'Please provide a valid email'],
  },
  avatar: {
    type: String,
  },
  role: {
    type: String,
    enum: ['user', 'admin'],
    default: 'user',
  },
  password: {
    type: String,
    required: [true, 'Please provide a password'],
    minLength: 8,
    select: false,
  },
  passwordConfirm: {
    type: String,
    required: [true, 'Please confirm your password'],
    validate: {
      validator: function (el) {
        return el === this.password;
      },
      message: 'Passwords are not the same',
    },
  },
  passwordChangedAt: Date,
  posts: [] // ???????????????
});

发布模型

const postSchema = new mongoose.Schema({
  title: {
    type: String,
    required: [true, 'A post must have a title'],
  },
  author: {
    type: String,
    required: [true, 'A post must have a title'],
  },
  likes: {
    type: Number,
    default: 10,
  },
  comments: {
    type: [String],
  },
  image: {
    type: String,
  },
  postBody: {
    type: String,
    required: [true, 'A post must contain a body'],
  },
  createdAt: {
    type: Date,
    default: Date.now(),
    select: false,
  },
});

现在我不知道这是否是最好的方法,但我正在考虑在 userSchema 中使用 postSchema 数组类型的字段,所以我将拥有为每个用户创建自己的帖子。我可以这样做吗?如果不是我怎么能做到这一点? 我应该使用搜索参数字段来过滤作者的帖子吗?我真的很困惑我应该如何处理这种情况。谢谢各位

【问题讨论】:

    标签: node.js mongoose mongoose-schema


    【解决方案1】:

    看看这个例子

    const UserSchema = new mongoose.Schema({
        username: String,
        posts: [{
          type: mongoose.Schema.Types.ObjectId,
          ref: 'Post'
        }]
      })
    
    const PostSchema = new mongoose.Schema({
        content: String,
        author: {
          type: mongoose.Schema.Types.ObjectId,
          ref: 'User'
        }
      })
    
    const Post = mongoose.model('Post', PostSchema, 'posts');
    const User = mongoose.model('User', UserSchema, 'users');
    
    module.exports = { User, Post };
    
    

    信用:https://medium.com/@nicknauert/mongooses-model-populate-b844ae6d1ee7

    【讨论】:

    • 谢谢,我会尝试在我的项目中实现它
    • 是的,这正是我想要的。现在我正在学习更多关于 Mongo DB 中的关系。谢谢
    • 很高兴帮助@Adrian!你能标记/接受我的回答吗?谢谢!
    • 对不起,我现在接受了。我是新手
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-02-16
    • 2023-03-13
    • 2021-02-23
    • 2014-11-14
    • 1970-01-01
    • 1970-01-01
    • 2019-10-30
    相关资源
    最近更新 更多