如何将用户模型ObjectId添加到Profile模型

时间:2019-04-19 06:43:50

标签: express mongoose

当我使用用户模型创建新用户时,它将为该用户创建一个新的对象ID。我也希望在用户创建个人资料时通过user: someUserId在我的个人资料模型中引用同一用户ID。

我的个人资料模型带有通过Schema.Types.ObjectId引用我的用户模型的对象,我也尝试填充。

创建配置文件时,我希望它也显示用户:usersID,但是创建配置文件时,它仅具有配置文件ID。

const profileSchema = new Schema({
  user: {
    type: Schema.Types.ObjectId,
    ref: "User"
  },
  username: {
    type: String,
    required: true,
    unique: true,
    minlength: 2,
    maxlength: 50
  },
  email: {
    type: String,
    minlength: 2,
    maxlength: 50,
    required: true,
    unique: true
  },
  gender: {
    type: String
  },
  location: {
    type: String
  },
  bio: {
    type: String,
    minlength: 2,
    maxlength: 255
  },
  favoriteBands: [nameSchema],
  favoriteGenres: [nameSchema],
  instruments: [instrumentSchema], // schema
  experience: [experienceSchema], // schema
  education: [educationSchema], // schema
  social: socialSchema,
  dateCreated: {
    type: Date,
    default: Date.now
  }
});

const Profile = mongoose.model("Profile", profileSchema);
module.exports = Profile;

我想查询一个用户ID,而不是在findOne方法中查询电子邮件。

router.post("/", auth, async (req, res, next) => {
  const { error } = validateProfile(req.body);
  if (error) return res.status(400).send(error.details[0].message);

  let profile = await Profile.findOne({ email: req.body.email });

  if (profile) {
    next(errors.processReq);
  } else {
    profile = new Profile({ ...req.body });
  }

  await profile.save();

  res.json(profile);
});

0 个答案:

没有答案
相关问题