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

wz8daaqr  于 12个月前  发布在  Go
关注(0)|答案(1)|浏览(190)

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

const PatientSchema = new Schema<patientType>({
    name: {
        type: String,
        required: [true, 'please provide a product name'],
        maxlength: 50,
        minlength: 3
    },
    email: {
        type: String,
        required: [true, 'please provide an email'], 
        match: [
            /^(([^<>()[\]\\.,;:\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,}))$/,
            'Please provide a valid email',
          ],
          unique: true,
    },
    password: {
        type: String,
        required: [true, 'please provide a password'],
        minlength: 8
    },
    phone: {
        type: Number,
        default: 0 
    },
    photo: {
        type: String
    },
    role: {
        type: String,
    },
    gender: {
        type: String,
        enum: ["male", "female", "other"]
    },
    bloodtype: {
        type: String
    },
    appointments: [{
        type: mongoose.Types.ObjectId,
        ref: 'Booking',
        required: true
    }]
})

字符串
医生型号:

const DoctorSchema = new Schema<doctorType>({
    name: {
        type: String,
        required: [true, 'please provide a product name'],
        maxlength: 50,
        minlength: 3
    },
    email: {
        type: String,
        required: [true, 'please provide an email'], 
        match: [
            /^(([^<>()[\]\\.,;:\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,}))$/,
            'Please provide a valid email',
          ],
          unique: true,
    },
    password: {
        type: String,
        required: [true, 'please provide a password'],
        minlength: 8
    },
    phone: {
        type: Number,
        default: 0 
    },
    photo: {
        type: String
    },
    role: {
        type: String,
    },
    ticketPrice: {
        type: Number,
        default: 1000,
        required: true
    },
    specialization: {
        type: String,
    },
    qualifications: {
        type: [Object],
    },
    experiences: {
        type: [Object]
    },
    bio: {
        type: String,
        minlength: 5,
    },
    about: {
        type: String,
        minlength: 4
    },
    reviews: [{                         //where i referenced the review model
        type: mongoose.Types.ObjectId, 
        ref: "Review",
        required: true,
        default: []
    }],
    averageRating: {
        type: Number,
        default: 0
    },
    totalRatings: {
        type: Number,
        default: 0
    },
    isApproved: {
        type: String,
        enum: ["pending", "approved", "cancelled"],
        default: 'pending'
    },
    appointments: [{
        type: mongoose.Types.ObjectId,
        ref: 'Booking',
        required: true
    }]
    
})


评论模型:

const ReviewSchema = new Schema<reviewType>({
    doctor: {
        type: mongoose.Types.ObjectId,
        ref: "Doctor",
    },
    patient: {
        type: mongoose.Types.ObjectId,
        ref: "User",
    },
    text: {
        type: String,
        required: [true, 'please add a review text'],
    },
    rating: {
        type: Number,
        required: true,
        min: 0,
        max: 5,
        default: 0,
    },
},{ timestamps: true });


患者创建医生审查功能:

const postDoctorReviews = async (req: MyUserRequest, res: Response) => {
    const {id: doctorId} = req.params
    const {patientId} = req.user

    const {text, rating} = req.body

    if(!text || !rating){
        throw new BadRequestError('Field cannot be empty')
    }

    const doctorReview = await Review.create({doctor: doctorId, patient: patientId, ...req.body})
    
    const doctor = await Doctor.findById(doctorId)
    doctor?.save()
    
    res.status(StatusCodes.CREATED).json({doctorReview})  
}

ttvkxqim

ttvkxqim1#

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

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

字符串
对此:

const doctor = await Doctor.findByIdAndUpdate(doctorId,
{
   $push: {
      reviews: doctorReview._id
   }
},{new:true});

相关问题