【问题标题】:Referencing another schema's property in Mongoose?在 Mongoose 中引用另一个模式的属性?
【发布时间】:2022-01-21 03:51:54
【问题描述】:

考虑以下几点:

我有一个User 架构:

const UserSchema = new mongoose.Schema(
  {
    email: {
      type: String,
      required: true,
      trim: true,
      lowercase: true,
      index: { unique: true },
      validate: {
        validator: emailValidator.validate,
        message: props => `${props.value} is not a valid email address!`
      }
    },
    password: {
      type: String,
      required: true,
      trim: true,
      index: { unique: true },
      minlength: 7,
      maxlength: 11
    },
    roles: [{ type: 'String' }],
    isVerified: { type: Boolean, default: false },
    passwordResetToken: String,
    resetPasswordExpires: Date
  },
  {
    timestamps: true
  }
);


export default mongoose.models.User || mongoose.model('User', UserSchema)

我有一个Profile 架构:

const ProfileSchema = new Schema({
  name: {
    type: String,
  },
  email: {
    type: Schema.Types.ObjectId, ref: 'User',
  },
  password: {
    type: Schema.Types.ObjectId, ref: 'User',
  },
  interestedActivities: {
    type: String,
  },
  memerSince: { type: Date, default: Date.now }
})


export default mongoose.models.Profile || mongoose.model('Profile', ProfileSchema)

以上内容是否会自动使用来自用户的email 和Password 填充ProfileSchema?

所以在我的route/api 例如/api/profile 例如,它会隐含地知道两者是链接的吗?

如果我这样做了:

从../../models/Profile导入配置文件

handler
  .use(auth)
  .get((req, res) => {
     Profile.findOne(
    {
      email: req.body.email
    },
  });


export default handler

它应该返回在用户中创建的电子邮件?

提前致谢!

【问题讨论】:

    标签: mongoose mongoose-schema


    【解决方案1】:

    不,它不会自动填充e-mail 和password。您也不能将电子邮件分配给reference 地点。如果您尝试这样做,您将获得Validation Error。因为你刚刚定义为ObjectId;

      email: {
        type: Schema.Types.ObjectId, ref: 'User',
      }
    

    ref 返回userId,您可以使用此userId 进行填充。像这样:

    handler
      .use(auth)
      .get((req, res) => {
         Profile.findOne(
        {
          userId: req.body.userId
        },
      }).populate('userId').select('email password bla bla');
    
    
    export default handler
    

    【讨论】:

      猜你喜欢
      • 2013-08-02
      • 2015-05-18
      • 1970-01-01
      • 2020-07-16
      • 2020-01-05
      • 1970-01-01
      • 2021-07-31
      • 2014-10-23
      • 1970-01-01
      相关资源
      最近更新 更多