in my node app, I need to add 2 elements to an array 'roles', which belongs to collection 'users'. I'm using native mongodb driver. Here is my code:
MongoClient.connect(url, function (err, db) {
if (err) {
console.log('Unable to connect to the mongoDB server. Error:', err);
} else {
console.log('Connection established to', url);
var collection = db.collection('users');
var roles = req.body.requestedRoles.split(',');
roles.forEach(function(role){
collection.update(
{
email: req.body.userEmail
},
{
$push: { roles: role }
},
{upsert: true},
function(err, result) {
if (err) {
console.log('err: ' + err);
}
else {
console.log('update result: ' + result);
}
}
);
});
collection.update(
{
email: req.body.userEmail
},
{
$push: { roles: req.body.requestedRoles }
},
{upsert: true},
function(err, result) {
if (err) {
console.log('err: ' + err);
}
else {
console.log('update result: ' + result);
}
}
);
}
});
req.body.requestedRoles contains "role-1,role-2"
When this code runs, I end up with the following 3 (instead of 2) roles: 'role-1', 'role-2', 'role-1,role-2'
Obviously, I do not need that third entry. What can I change to avoid this?