I have encountered an issue while trying to generate unique passwords for each document in a MongoDB collection. The current function I am using, however, generates the same password for every user.
Below is the code snippet that I am working with:
function createPasswords(){
db.collection('users').updateMany({}, {$set:{password: GeneratePassword(12, false)}});
}
My expectation was for the GeneratePassword
function to run for individual documents, but it appears to only execute once, resulting in identical random passwords for all users in the collection.
Therefore, my question is how can I modify this setup to generate distinct passwords for each user simultaneously using updateMany
.
It's worth mentioning that the GeneratePassword
function is not a custom implementation, but rather utilizes the password-generator
package.
Thank you in advance!
UPDATE
I attempted the following code based on turivishal's response provided below.
db.collection('users').updateMany({},[{
$set: { updated: 'true',
password: {
$function: {
body: function() {
$function: {
function passGen(param1, param2) {
return GeneratePassword(param1,param2)
}
return passGen(12, false);
}
},
args: [],
lang: "js"
}
}
}
}]);
When executing this code, it resulted in the following error:
MongoServerError: Invalid $set :: caused by :: The body function must be specified.
If anyone could point out what might be going wrong here, any guidance would be greatly appreciated.