我在数据库e.i中有描述产品的数组。 [aaa,bbb,ccc]我想在我的数组中添加新项目,如[aaa,bbb,ccc,ddd],但是我的代码没有向数组中添加新项目只是更改现有数组,如[ddd]。 问题:在我的代码中我应该更改为现有数组添加新项目?
index.html
<form name="editProduct.addForm" ng-submit="editProduct.addDescription(addDescription, editProduct.addForm.addDescription.$valid)" novalidate>
<div ng-class="{ 'has-success':(editProduct.addForm.addDescription.$valid && !editProduct.addForm.addDescription.$pristine), 'has-error':(!editProduct.addForm.addDescription.$valid && !editProduct.addForm.addDescription.$pristine) || (!addForm.addDescription.$valid && addForm.$submitted) }">
<label><h4>Add description:</h4></label>
<strong><input class="form-control" type="text" name="addDescription" ng-model="addDescription" placeholder="Add description" required></strong>
</div>
<br>
<button ng-disabled="editProduct.disabled" class="btn btn-primary add-des" type="submit">Save</button>
</form>
api.js
router.put('/editProduct', function(req, res){
var editProduct = req.body._id;
if(req.body.addDescription) var addDescription = req.body.addDescription;
User.findOne({ username: req.decoded.username }, function(err, mainUser) {
if(err) throw err;
if(!mainUser) {
res.json({ success: false, message: 'User no found'});
} else {
if(addDescription){
if(mainUser.permission === 'admin') {
var options = { new: true };
Product.findOneAndUpdate({ _id: editProduct }, { description: addDescription }, options, function(err, product){
if(err) throw err;
if(!product){
res.json({ success: false, message: 'Product no found' });
} else {
product.update(function(err){
if(err){
console.log(err);
} else {
res.json({ success: true, message: 'Added new description'})
}
});
}
});
} else {
res.json({ success: false, message: 'You are not an admin'})
}
}
}
})
})
答案 0 :(得分:4)
您可以使用$ push运算符将新项目推送到这样的数组 -
Product.findOneAndUpdate(
{ _id: editProduct },
{ $push: {
description: addDescription
}}, options, function(err, product){
});