skip to Main Content

//** If I’m adding a new document with the name: "India", then I don’t want that the DB allow another name with the name: "INDIA", "india", "indIA", etc. I’m new and learning, help would be great!!**

// Controller

var Dinosaur = require('../models/dinosaurs');

//addDino
module.exports.addDino = (req, res) => {
    var name = req.body.name;
    var type = req.body.type;
    var height = req.body.height;
    var weight = req.body.weight;
    var Period = req.body.Period;

    req.checkBody('name', 'Name is required').notEmpty();

    var errors = req.validationErrors();
    if (errors)
        return res.status(400).send({
            message: 'Name is Required'
        });
    else {
        let newDino = {
            name: name,
            type: type,
            height: height,
            weight: weight,
            Period: Period
        }
        Dinosaur.addDino(newDino, (err, result) => {
            if (err) {
                if (err.name) return res.status(409).send({
                    message: name + ' Already Exist'
                });
                else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url });
                else return res.json(err, "Server Error");
            }
            else {
                return res.status(200).send({
                    message: "Done"
                });
            }
        });
    }
}

// Model

var mongoose = require('mongoose');

//dinosaur schema
var DinosaurSchema = mongoose.Schema({
    name: {
        type: String,
        unique: true
    },
    type: {
        type: String
    },
    height: {
        type: Number
    },
    weight: {
        type: Number
    },
    Period: {
        type: String
    }
});

var Dinosaur = mongoose.model('dinosaur', DinosaurSchema);

//add
module.exports.addDino = (query, callback) => {
    Dinosaur.create(query, callback);
}

// GetAll, Already Created a new document with the name "Brachiosaurus"

enter image description here

// > Create, a new create with the first letter lower case "brachiosaurus", Don’t want it to be pushed.
enter image description here

//Get All, Got pushed.
enter image description here

2

Answers


  1. Chosen as BEST ANSWER

    With the help of Apoorva & brainstorming for a bit, I come up with this solution.

    // Controller

    const { json } = require('express/lib/response');
    var Dinosaur = require('../models/dinosaurs');
    
    //addDino
    module.exports.addDino = (req, res) => {
        var name = req.body.name;
        var type = req.body.type;
        var height = req.body.height;
        var weight = req.body.weight;
        var Period = req.body.Period;
    
        req.checkBody('name', 'Name is required').notEmpty();
        var errors = req.validationErrors();
        if (errors)
            return res.status(400).send({
                message: 'Name is Required'
            });
        else {
            let newDino = {
                name: name.toLowerCase(),
                type: type,
                height: height,
                weight: weight,
                Period: Period
            }
    
            Dinosaur.addDino(newDino, (err, result) => {
                if (err) {
                    if (err.name) return res.status(409).send({
                        message: name + ' Already Exist'
                    });
                    else if (err.url) return res.json({ status: false, error: { url: "Url already exist" }, message: err.url });
                    else return res.json(err, "Server Error");
                }
                else {
                    return res.status(200).send({
                        message: "Done"
                    });
                }
            });
        }
    }
    
    //Update
    module.exports.updateDino = (req, res) => {
        let _id = req.body.id;
        let name = req.body.name;
        let type = req.body.type;
        let height = req.body.height;
        let weight = req.body.weight;
        let Period = req.body.Period;
    
        req.checkBody('name', 'Name is required').notEmpty();
        var errors = req.validationErrors();
        if (errors)
            return res.status(400).send({
                message: 'Name is Required'
            });
        else {
            var updateDino = {
                name: name.toLowerCase(),
                type: type,
                height: height,
                weight: weight,
                Period: Period
            }
    
            Dinosaur.updateDino({ _id: _id }, updateDino, (err, result) => {
                if (err) return res.json({ status: false, message: err });
                else
                    return res.status(200).send({
                        message: "Updated"
                    });
            });
        }
    }
    
    //delete
    module.exports.deleteDino = (req, res) => {
    
        let name = req.body.name;
        req.checkBody('name', 'Name is required').notEmpty();
        var errors = req.validationErrors();
        if (errors)
            return res.status(400).send({
                message: 'Name is Required'
            });
        else {
            Dinosaur.deleteDino(name.toLowerCase(), (err, result) => {
                if (err) {
                    return err;
                }
                else if (result.deletedCount == 0) {
                    res.status(400).send({
                        message: 'Not Found'
                    });
                }
                else
                    return res.status(200).send({
                        message: 'Deleted'
                    });
            });
        }
    }
    
    //GetByName
    module.exports.getDino = (req, res) => {
        let query = req.body.name;
        req.checkBody('name', 'Name is required').notEmpty();
        var errors = req.validationErrors();
        if (errors)
            return res.status(400).send({
                message: 'Name is Required'
            });
        else {
            Dinosaur.getDino({ name: query.name.toLowerCase() }, (err, result) => {
                if (err)
                    return res.status(400).json("Not Found");
                else if (result == null)
                    return res.status(400).json('Not Found');
                else {
                    return res.json(uppercase(result.name));
                }
            });
        }
    }
    
    module.exports.getAllDino = (req, res) => {
        var query = {};
        Dinosaur.listDino(query, (err, result) => {
            if (err)
                res.json(err);
            else
                return res.status(200).json(result);
        });
    }
    
    function uppercase(str) {
        var arr = str.toString().split(' ');
        var newarr = [];
    
        for (var i = 0; i < arr.length; i++) {
            newarr.push(arr[i].charAt(0).toUpperCase() + arr[i].slice(1));
        }
        return newarr.join(' ');
    }
    

    // Model*

    var mongoose = require('mongoose');
    
    //dinosaur schema
    var DinosaurSchema = mongoose.Schema({
        name: {
            type: String,
            unique: true
        },
        type: {
            type: String
        },
        height: {
            type: Number
        },
        weight: {
            type: Number
        },
        Period: {
            type: String
        }
    });
    
    DinosaurSchema.index({ user_id: 1, name: 1, res_type: 1, level: 1 }, { unique: true });
    
    var Dinosaur = mongoose.model('dinosaur', DinosaurSchema);
    
    //add
    module.exports.addDino = (query, callback) => {
        Dinosaur.create(query, callback);
    }
    //updateDino
    module.exports.updateDino = (query, data, callback) => {
        Dinosaur.findByIdAndUpdate(query, data, callback);
    }
    //remove
    module.exports.deleteDino = (query, callback) => {
        Dinosaur.deleteOne({ name: query }, callback)
    }
    //getDino   
    module.exports.getDino = (query, callback) => {
        Dinosaur.findOne(query, callback);
    }
    //getAllDino
    module.exports.listDino = (query, callback) => {
        Dinosaur.find(query, callback).sort({ "name": 1 });
    }
    

  2. just add lowercase prop to Schema.

    Schema

    const DinosaurSchema = mongoose.Schema({
        name: {
            type: String,
            unique: true,
            required: true,
            lowercase: true,
        },
        // ...
     )}
    
    

    first it will convert name into lowercase then it will look for duplicates. and it will throw error if it founds.

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search