Reputation: 631
I'm inserting a data into an array but when I insert the data, it overwrites the whole array, here is my router for updating array
router.put('/editbloodbankarray', function(req, res) {
var editUser = req.body._id;
var newName = req.body.bloodbank_array;
User.findOne({ _id: editUser }, function(err, user) {
if (err) throw err;
user.bloodbank_array = newName;
// Save changes
user.save(function(err) {
if (err) {
res.json({ success: false, message: 'error' });
} else {
res.json({ success: true, message: 'Name has been updated!' });
}
});
});
});
sample document:
_id:5c8521c377df3158d0555db1,
bloodbank_array:
[
0:"1"
1:"2"
]
When I update/insert new item for example: 3..the array turns to:
_id:5c8521c377df3158d0555db1,
bloodbank_array:
[
0:"3"
]
Upvotes: 1
Views: 32
Reputation: 303
You can use the $push operator to do it directly (look here for more information) but since you already lookup the document first, you could just do user.bloodbank_array.concat(newName);
instead of assigning a new value to the array like you do now with user.bloodbank_array = newName
. The concat-function is a standard JS-function which inserts a new item at the end of an array. Fore more information you may read the mozilla article.
Upvotes: 1
Reputation: 300
You are overwriting the existing array. Below is the line
user.bloodbank_array = newName;
Instead do a for loop on the newName array
and push the items in user.bloodbank_array
like
for(int i=0;i<newName.length;i++)
{
user.bloodbank_array.push(newName[i]);
}
Upvotes: 0