Skip to content

Instantly share code, notes, and snippets.

@amyonsun
Last active July 9, 2021 21:53
Show Gist options
  • Save amyonsun/ee501a6b76de924c1f654fa3e2f16f83 to your computer and use it in GitHub Desktop.
Save amyonsun/ee501a6b76de924c1f654fa3e2f16f83 to your computer and use it in GitHub Desktop.
Python, MongoDB - Add New User With Phone Number
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# Importing Libraries
from pymongo import MongoClient
from datetime import datetime
# NOTE: make sure to install pymongo[srv] too via "pip install pymongo[srv]"
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# Database Configuration
Cluster = MongoClient("mongodb+srv://<username>:<password>@<clustor>.<hostname>/<database-name>")
# Choose database
db = Cluster['main']
# Choose collection
users = db['users']
## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ## ##
# Main function
def add_user_with_phone_number(phone_number):
# Search phone number in database to fields be unique
search_for_phone_number = users.find_one({'phone_number':phone_number})
if search_for_phone_number is not None:
return [1, 'Phone number already in use.']
# New user model
new_user = {
'phone_number': phone_number,
'name': '',
'join_date': datetime.now()
# add fields as much as you need ...
}
try:
# try to add new_user to the database
added = users.insert_one(new_user)
# add ObjectId to the new_user dict
new_user['_id'] = added.inserted_id
# do whatever you want with new_user dict here (this is your user)
return [0, 'User added.']
# if error happends
except Exception as error:
return [1, 'Failed to add user: ' + str(error)]
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment