[solved] Modifying every instance of a specific field

Hello everyone, this is my first post on the forum. I started an internship a few weeks ago using the meteor framework. My latest task was to format phone numbers before they get sent to the db. Now that I have finished that I want to update all the existing users phone number to have the same format.

Here is an example of the collection
{ "_id" : "G4NjJaNRLpjkXqkfe", "Address" : { "zip" : "01960", "phone" : "1111111111" } }

I have a method that will take a phone number as a parameter and format it but I’m not really sure where to start as I’m not all that familiar with MongoDB. I figured I would ask here first and see if I can figure it out with some direction before bugging my lead dev, thank you.

Hi!
I think it can be possible with RegExp query

You’d probably want to do a Meteor.users.find() to get a list of all users that have something in the phone field (for this, google ‘mongo exist’). Something like:

const usersWithPhones = Meteor.users.find({ phone: { $exists: true } });

And then go over this list one by one with something like this:

usersWithPhones.forEach((user) => {
  const modifiedPhone = myFuncToGetModifiedPhone(user.phone);
  // write modifiedPhone to DB here using user._id
});
2 Likes

Done similar stuff before - @vooteles has suggested code similar to what I use.

I simply do this on my startup hook -

	const allUsers = Meteor.users.find().fetch();
	allUsers.forEach(({ _id, phone }) => {
		const formatedPhone = methodToFormatPhone(phone);
		Meteor.users.update(
			{ _id },
			{ phone: formatedPhone }
		);
	});

1 Like

Hey guys, seen these replies a little late but it looks like I came up with the right solution.

Meteor.startup(function () {
  Workers.find().forEach((e) => {
    if (e.Address && e.Address.Phone) {
      Workers.update({ _id: e._id }, { '$set': { 'Address.Phone': phoneFormatter.format(e.Address.Phone, "NNN-NNN-NNNN") } })
    }
  });
});