我试图将一个项目添加到一个数组并返回更新的模型。
我这样提出我的要求:
addCarToDriver(CarToAdd) {
const self = this;
request
.put('api/drivers/' + this.state.race._id)
.send({
car: CarToAdd})
.end(function(err, res) {
console.log(res.body);
self.setState({race: res.body});
});
}
它在服务器上点击:
MyRace.findByIdAndUpdate(
req.params.myrace_id,
{ $push: { 'cars': req.body.car } },
function(er, model) {
if (er) {
console.log(err);
return res.send(err);
}
console.log(model);
return res.json(model);
});
现在在请求回调中,我希望记录新的更新模型,即使用新的Car
。它不是。 " old"版本记录。但是,如果我刷新页面,模型将使用新车进行更新。
当然我需要在回调中直接设置state。关于如何做到这一点的任何提示?
答案 0 :(得分:3)
Mongoose 4 has changed ''' Form used in patient registration. Extends UserCreationForm '''
class PatientRegisterForm(UserCreationForm):
email = EmailField(required = True)
insurance_id = forms.CharField(required=True, label="Insurance ID")
insurance_provider = forms.CharField(required=True, label="Insurance Provider")
class Meta:
model = User
fields = ("email", "password1", "password2", "Insurance ID", "Insurance Provider")
def clean_password2(self):
password1 = self.cleaned_data.get("password1")
password2 = self.cleaned_data.get("password2")
if password1 and password2 and password1 != password2:
raise forms.ValidationError(
self.error_messages['password_mismatch'],
code='password_mismatch',
)
return password2
def save(self, commit=True):
user=super(UserCreationForm, self).save(commit=False)
user.set_password(self.clean_password2())
user.insurance_id = self.cleaned_data["insurance_id"]
user.insurance_provider = self.cleaned_data["insurance_provider"]
if commit:
user.save()
return user
''' This displays the patient login form. Unique because of insurance numbers '''
def patient_registration(request):
if request.POST:
form = PatientRegisterForm(request.POST)
if form.is_valid():
new_user = form.save()
new_patient = Patient(user = new_user)
new_patient.save()
temp= Event(activity= '\n'+new_patient.user.get_full_name()+" has registered as a patient ")
temp.save()
return HttpResponseRedirect('/login/') # TODO : Refer them to there home page
else:
return HttpResponseRedirect('/login/') # TODO : Ditto ^^^
else:
form = PatientRegisterForm()
return render(request, "main_site/patient_registration.html", {"form":form})
行为会返回旧文档,如果您想要新的更新版本,则需要传递.findAndUpdate
,because that was the actual behavior in MongoDB
您可以修补查询以将{new:true}
设置为旧的方式:
options.new=true