Search code examples
mongodbvue.jsvalidationmongoosemongoose-schema

How to set validation for UNIQUE fields in MongoDB, Vuejs?


I'm new to MongoDB and Vuejs. I'm not sure if it is possible that I was trying to set validation for Unique value, but somehow it does not work.

My defined schema from back-end:

const uuid = require("uuid");
const mongoose = require("mongoose");
const Schema = mongoose.Schema;

let informationSchema = new Schema ({
    _id: {type: String, default: uuid.v1},
    firstName: {                                    
        type: String, required:true, trim: true, unique: true
    },
    lastName: {                                     
        type: String, required:true, trim: true, unique: true
    }
});

module.exports = mongoose.model('informations', informationSchema)

My action form in Vuejs from Front-end:

<template>
    <div class="row justify-content-center">
        <div class="col-md-6">
            <h3 class="text-center">Create Name</h3>
            <form @submit.prevent="handleSubmitForm">
                <div class="form-group">
                    <label>First Name</label>
                    <input type="text" class="form-control" v-model="name.firstName" required>
                </div>
                <div class="form-group">
                    <label>Last Name</label>
                    <input type="text" class="form-control" v-model="name.lastName" required>
                </div>
                <button class="btn btn-danger mt-3">Create</button>
            </form>
        </div>
    </div>
</template>

<script>
    import axios from "axios";

    export default {
        data() {
            return {
                name: {
                   firstName: '',
                   lastName: ''  
                }
            }
        },
        methods: {
            handleSubmitForm() {
                let apiURL = 'http://localhost:3000/name';
                
                axios.post(apiURL, this.student).then(() => {
                    console.log(res)
                }).catch(error => {
                    console.log(error)
                });
            }
        }
           
    }
</script>

My 1st inserted data: [{"firstName":"ABC", "lastName": "DCF"}] I want to insert the 2nd one with data : firstName = "ABC", but last name = "XYZ". The error for validation occured because of validation (Unique) set in the defined schema from back-end).

My expected output:

Is there any possible ways to do:

  1. If I insert the 1st data, it will work.
  2. If I insert the 2nd data same as the 1st data, the error for validation will occur.
  3. If I insert the 3rd data that is different from lastName only, it will work.

Thank you so much.


Solution

  • First of all, Mongo and Vue are completly separated, there is no relation.

    Answering your question, the validation fail because you are telling mongo "Set firstName and lastName as unique fields". But not "Set these fields unique TOGETHER". So when you add a firstname, the second attemp try to add an existing firstName and fails.

    So you can create a unique index:

    informationSchema.index({ firstName: 1, lastName: 1 }, { unique: true });
    

    And remove unique constraint in the schema.