我有这个猫鼬模式:
<div class="dropdown">
<button class="btn btn-danger dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false">
Select vehicle type
</button>
<div class="dropdown-menu" aria-labelledby="dropdownMenuButton">
@foreach($vehicles as $vehicle)
<a class="dropdown-item" href="#">{{ $vehicle->type }}</a>
@endforeach
</div>
</div>
</div>
@foreach($services as $service)
<div class="card mt-3">
<div class="card-body">
<div class="d-flex justify-content-between">
<h4 class="card-title">{{ $service->nom }}</h4>
{{--this is where I'd like to use the selected vehicle type to simply add it to
the service price. If i do: {{ $service->price + $vehicle->price }} it chooses
the last one that went through the foreach loop --}}
<h3>{{ $service->price }}$</h3>
</div>
<p class="card-text">{{ $service->description }}</p>
</div>
</div>
@endforeach
我先找用户,因为我要给用户授权。现在我想更新一些部分。只是想清楚,我想更新找到的用户文档的某些部分。
我有多个民意调查,用户可以在每个民意调查中投票给多个候选人。所以如果用户根本没有投票,votes 数组将为空,我们必须先推送 pollId 和他/她投票的第一个候选人 ID。如果 pollId 存在,我们必须首先通过 pollId 找到该子文档,然后我们应该在候选数组中添加 candidateId。
我该怎么做?首选只是一个操作而不是多个操作。如果我能更新用户,那就更好了。
如果不清楚,请告诉我。我会尽量解释更多。
谢谢。
答案 0 :(得分:0)
我会做这样的事情
function updateUsersVotes(userId, newVote) {
User.findById(userId)
.exec()
.then((dbUser) => {
if (!dbUser.votes.length) { // no votes yet
dbUser.votes.push(newVote);
} else { // check current votes
const voteIndex = dbUser.votes.findIndex((vote) => vote.pollId.toString() === newVote.pollId.toString());
if (voteIndex > 0) { // if the incoming vote pollId matches an existing pollId
dbUser.votes[voteIndex].candidates.push(...newVote.candidates);
} else {
dbUser.votes.push(newVote); // if the incoming pollId can't be found, then add it.
}
}
dbUser.save({ validateBeforeSave: true }); // update the user.
})
.catch((error) => {
handleError(error); // you should always handle your errors.
});
}