//** 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"
// > Create, a new create with the first letter lower case "brachiosaurus", Don’t want it to be pushed.
2
Answers
With the help of Apoorva & brainstorming for a bit, I come up with this solution.
// Controller
// Model*
just add
lowercase
prop to Schema.Schema
first it will convert name into lowercase then it will look for duplicates. and it will throw error if it founds.