mongoose 如何通过在另一个模型中创建文档来直接更新mongodb中的引用模型?

wz8daaqr  于 2024-01-08  发布在  Go
关注(0)|答案(1)|浏览(253)

好的,我的API中有3个模型,Patient,Doctor和Reviews。我在Doctor模型中引用了Reviews模型。这个想法是,患者可以使用Review.create()为特定的医生发布评论。然而,在创建文档之后,由于在Doctor模型中引用了Review模型,医生模型中的“reviews”属性也应该自动更新。2似乎无法实现这一点。
患者型号:

  1. const PatientSchema = new Schema<patientType>({
  2. name: {
  3. type: String,
  4. required: [true, 'please provide a product name'],
  5. maxlength: 50,
  6. minlength: 3
  7. },
  8. email: {
  9. type: String,
  10. required: [true, 'please provide an email'],
  11. match: [
  12. /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  13. 'Please provide a valid email',
  14. ],
  15. unique: true,
  16. },
  17. password: {
  18. type: String,
  19. required: [true, 'please provide a password'],
  20. minlength: 8
  21. },
  22. phone: {
  23. type: Number,
  24. default: 0
  25. },
  26. photo: {
  27. type: String
  28. },
  29. role: {
  30. type: String,
  31. },
  32. gender: {
  33. type: String,
  34. enum: ["male", "female", "other"]
  35. },
  36. bloodtype: {
  37. type: String
  38. },
  39. appointments: [{
  40. type: mongoose.Types.ObjectId,
  41. ref: 'Booking',
  42. required: true
  43. }]
  44. })

字符串
医生型号:

  1. const DoctorSchema = new Schema<doctorType>({
  2. name: {
  3. type: String,
  4. required: [true, 'please provide a product name'],
  5. maxlength: 50,
  6. minlength: 3
  7. },
  8. email: {
  9. type: String,
  10. required: [true, 'please provide an email'],
  11. match: [
  12. /^(([^<>()[\]\\.,;:\s@"]+(\.[^<>()[\]\\.,;:\s@"]+)*)|(".+"))@((\[[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\.[0-9]{1,3}\])|(([a-zA-Z\-0-9]+\.)+[a-zA-Z]{2,}))$/,
  13. 'Please provide a valid email',
  14. ],
  15. unique: true,
  16. },
  17. password: {
  18. type: String,
  19. required: [true, 'please provide a password'],
  20. minlength: 8
  21. },
  22. phone: {
  23. type: Number,
  24. default: 0
  25. },
  26. photo: {
  27. type: String
  28. },
  29. role: {
  30. type: String,
  31. },
  32. ticketPrice: {
  33. type: Number,
  34. default: 1000,
  35. required: true
  36. },
  37. specialization: {
  38. type: String,
  39. },
  40. qualifications: {
  41. type: [Object],
  42. },
  43. experiences: {
  44. type: [Object]
  45. },
  46. bio: {
  47. type: String,
  48. minlength: 5,
  49. },
  50. about: {
  51. type: String,
  52. minlength: 4
  53. },
  54. reviews: [{ //where i referenced the review model
  55. type: mongoose.Types.ObjectId,
  56. ref: "Review",
  57. required: true,
  58. default: []
  59. }],
  60. averageRating: {
  61. type: Number,
  62. default: 0
  63. },
  64. totalRatings: {
  65. type: Number,
  66. default: 0
  67. },
  68. isApproved: {
  69. type: String,
  70. enum: ["pending", "approved", "cancelled"],
  71. default: 'pending'
  72. },
  73. appointments: [{
  74. type: mongoose.Types.ObjectId,
  75. ref: 'Booking',
  76. required: true
  77. }]
  78. })


评论模型:

  1. const ReviewSchema = new Schema<reviewType>({
  2. doctor: {
  3. type: mongoose.Types.ObjectId,
  4. ref: "Doctor",
  5. },
  6. patient: {
  7. type: mongoose.Types.ObjectId,
  8. ref: "User",
  9. },
  10. text: {
  11. type: String,
  12. required: [true, 'please add a review text'],
  13. },
  14. rating: {
  15. type: Number,
  16. required: true,
  17. min: 0,
  18. max: 5,
  19. default: 0,
  20. },
  21. },{ timestamps: true });


患者创建医生审查功能:

  1. const postDoctorReviews = async (req: MyUserRequest, res: Response) => {
  2. const {id: doctorId} = req.params
  3. const {patientId} = req.user
  4. const {text, rating} = req.body
  5. if(!text || !rating){
  6. throw new BadRequestError('Field cannot be empty')
  7. }
  8. const doctorReview = await Review.create({doctor: doctorId, patient: patientId, ...req.body})
  9. const doctor = await Doctor.findById(doctorId)
  10. doctor?.save()
  11. res.status(StatusCodes.CREATED).json({doctorReview})
  12. }

ttvkxqim

ttvkxqim1#

不幸的是,doctor?.save()不会自动更新引用。您需要手动将Review._id推入Doctor.reviews数组。
更改此:

  1. const doctor = await Doctor.findById(doctorId)
  2. doctor?.save()

字符串
对此:

  1. const doctor = await Doctor.findByIdAndUpdate(doctorId,
  2. {
  3. $push: {
  4. reviews: doctorReview._id
  5. }
  6. },{new:true});

展开查看全部

相关问题