Question

I am currently working on a Flask and Heroku application and I use a MongoDB to save user signup information. The problem I am having is that when I try to save an email it gives me the error:

InvalidDocument: key 'email@domain.com' must not contain '.'

I would also like to know how to ensure that each email is unique and is not previously in the database, without having to query the db.

Here is the code I have so far:

import os
import re
from pymongo import MongoClient
from flask import Flask, render_template, request, session, redirect
import jinja2

email_regex = re.compile(r"^[\S]+@[\S]+\.[\S]+$")
password_regex = re.compile(r'^[a-zA-Z]\w{3,14}$')

client = MongoClient("mongodb://<user>:<password>@linus.mongohq.com:11077/users")
db = client.get_default_database()
users = db.users


app = Flask(__name__)
@app.route('/signup', methods=['GET','POST'])
def signup():
    if request.method == 'POST':
        email = request.form.get('email')
        name = request.form.get('name')
        password = request.form.get('password')
        v_password = request.form.get('v_password')
        if email == '' or name == '' or password=='' or v_password =='':
            return render_template('signup.html', b_error="Cannot leave any field blank")
        elif not(email_regex.match(email)):
            return render_template('signup.html', e_error="Please enter valid email!")
        elif not(password_regex.match(password)):
            return render_template('signup.html', p_error="Please enter valid password")
        elif password != v_password:
            return render_template('signup.html', m_error="Passwords do not match")
        else:
            users.insert({name:name, email:email,password:password})
            return redirect('/')
    return render_template('signup.html')

Is there anyway that I can set up a model for the db to follow so that I can set the emails to be unique, make the fields not required/required, and allow me to save emails?

Was it helpful?

Solution

The best way to ensure that a value in a collection is unique is to use a unique index.

In the MongoDB shell it would be:

db.users.ensureIndex({email: 1, unique: true})

Using PyMongo it's something like:

users.ensure_index([('email', 1)], unique=True)

The 1 in these examples orders values in the index in ascending order. This should be sufficient for your use. PyMongo offers pymongo.ASCENDING and pymongo.DESCENDING as conveniences.

More details are available in the docs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top