Friday 19 May 2017

Mongoose saving empty record despite schema "require"

I'm creating a Node.js app that uses Mongoose and Express to create a RESTful API. The Mongoose schema defines required fields; however, when I submit an empty POST via Postman, the API creates empty records. Why isn't Mongoose / MongoDB preventing a save based on my schema?

I'm just learning node.js / express / mongoose / mongodb and coming from a mySQL/MSSQL world so I may be thinking about schema required fields the wrong way (i.e. like a database constraint)

Here is my router:

// Initialize controller(s) for CRUD
var customer = require('../controllers/customercontroller');  

// Initialize Router
var express = require('express');
var router = express.Router();

router.get('/:id', function(req, res) {
    console.log("Customer Requested");

    customer.read(req,res);
});

router.get('/', function(req, res) {
    console.log("Customer List Requested");
    customer.getList(req,res);
});

router.put("/:id", function(req, res){
console.log ("Updating Customer");
    customer.update(req,res);

});

router.post("/", function(req, res){
console.log ("Creating Customer");
    customer.create(req,res);

});

router.delete("/:id", function(req, res){
console.log ("Delete Customer");
    customer.delete(req,res);
});

module.exports = router;

Here is my controller:

var Customer = require('../models/customermodel');

exports.getList = function (req, res) {
    Customer.find({}, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.create = function (req, res) {
    var customer = new Customer(req.body);
    customer.save(function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.read = function (req, res) {
    Customer.find(req.params.id, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.update = function (req, res) {
    Customer.findOneAndUpdate(req.params.id, function (err, customer) {
        if (err)
            res.send(err);
        res.json(customer);
    });
};

exports.delete = function (req, res) {
    Customer.remove({_id: req.params.id}, function (err, customer) {
        if (err)
            res.send(err);
        res.json({ message: 'Customer deleted'});
    });
};

And here is my model:

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/hs_db');

var Schema = mongoose.Schema;

var CustomerSchema = new Schema({
    "name": { type: String, Required: 'Required: name' },
    "alias": { type: String, Required: 'Required: alias' },
    "email": { type: String, Required: 'Required: email' },
    "address1": { type: String, Required: 'Required: address1' },
    "address2": { type: String, Required: 'Required: address2' },
    "address3": { type: String, Required: 'Required: address3' },
    "city": { type: String, Required: 'Required: city' },
    "state": { type: String, Required: 'Required: state' },
    "postcode": { type: String, Required: 'Required: postcode' },
    "country": { type: String, Required: 'Required: country' },
    "created": { type: Date, Required: 'Required: date' },
});

module.exports = mongoose.model('customer', CustomerSchema);

When I post an empty body with Postman and query the result with the mongo console:

> db.customers.find()
{ "_id" : ObjectId("591f25ae0cca8f5148cce551"), "__v" : 0 }
{ "_id" : ObjectId("591f25d40cca8f5148cce552"), "__v" : 0 }
{ "_id" : ObjectId("591f25f00cca8f5148cce553"), "__v" : 0 }
{ "_id" : ObjectId("591f2764dc5a191fe8730ccd"), "__v" : 0 }
>

SO, my question:

Isn't the schema supposed to validate the data and prevent the save similar to a database constraint in mySQL or MSSQL? Or does the schema just give data for a node.js controller to reference, requiring me to create business logic to enforce the constraint?



via hoekma

No comments:

Post a Comment