在 Mongoose 中引用另一个模式的 属性?

Referencing another schema's property in Mongoose?

考虑以下因素:

我有一个 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)

以上是否会自动用用户的 emailPassword 填充 ProfileSchema

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

如果我这样做的话:

../../models/Profile

导入配置文件
handler
  .use(auth)
  .get((req, res) => {
     Profile.findOne(
    {
      email: req.body.email
    },
  });


export default handler

应该return在用户中创建的电子邮件?

提前致谢!

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

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

A ref returns 和 userId,您可以使用此 userId 进行填充。像这样:

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


export default handler