Answer the question
In order to leave comments, you need to log in
How to add a new element to an array and change one of them in the array?
Good day!
I need to update one element in an array and add a new element.
This is necessary to install a new car for the driver.
My view:
<div class="form-group" ng-class="{ 'has-error' : submitted && driverForm.car.$invalid }">
<label mean-token="'edit-car'" class="col-md-2 control-label">Авто</label>
<div class="col-md-10">
<select name="car" id="car" ng-model="selectedCar" class="form-control">
<option ng-repeat="option in cars" value="{{option._id}}">
{{option.model +' - '+ option.number}}
</option>
</select>
</div>
</div>
$scope.update = function(isValid) {
if (isValid) {
var driver = $scope.driver;
if (!driver.updated) {
driver.updated = [];
}
driver.updated.push(new Date().getTime());
driver.user = MeanUser.user;
driver.acl = MeanUser.acl;
var newCar = currentCar($scope.selectedCar);
var oldCar = _(driver.cars).filter({'current': true}).map(function (item) {
item.current = false;
return item;
}).value()[0];
driver.cars.push(newCar;
driver.$update(function() {
console.log('driver.cars: ', driver.cars);
$location.path('drivers/' + driver._id);
});
}
else {
$scope.submitted = true;
}
};
function currentCar (car) {
return {
date: new Date(),
car: car._id,
current: true
}
}
var DriversSchema = new Schema({
name: {
type: String,
required: true,
trim: true,
unique: true,
dropDups: true
},
id: {
type: Number,
required: true,
unique: true,
dropDups: true
},
cars: [{
current: Boolean,
car: {
type: Schema.ObjectId,
ref: 'Car'
},
date: Date
}],
...
update: function(req, res) {
var driver = _.extend(req.driver, req.body);
console.log('Update driver ', driver);
driver.cars = _(driver.cars).map(function (item) {
console.log(item);
item.car = mongoose.Types.ObjectId(item.car);
return item;
}).value();
driver.save(function(err, response) {
if (err) {
console.log('Error on update drivers car ' + err);
return res.status(500).json({
error: 'Cannot update the driver'
});
}
res.json(driver);
});
},
[{
current: Boolean, // текущий авто
car: {
type: Schema.ObjectId,
ref: 'Car'
},
date: Date
}]
Answer the question
In order to leave comments, you need to log in
Didn't find what you were looking for?
Ask your questionAsk a Question
731 491 924 answers to any question