简体   繁体   中英

Mongoose validation triggers error but data is still stored

The mongoose documentation claims that if validation fails it will not store the data. However the following code does store invalid data posted to /api/orders. The console.write does print the expected error but the data is already in the database at that point.

http://mongoosejs.com/docs/api.html#document_Document-validate "This method is called pre save and if a validation rule is violated, save is aborted and the error is returned to your callback."

code:

app.post('/api/orders', function(req, res) {
    var OrderItem = new Order(req.body);
    OrderItem.save(function (err) {
        if (err) {
            console.log(req.body);
            console.log(err);
        }
        res.send(OrderItem);
    });
});

var orderSchema = mongoose.Schema({
    user: {type: String, required: true, match: /^[a-zA-Z]{1,8}$/}, //\p{L}
    lines: [{
        name: String,
        count: {type: Number, required: true, min: 0, max: 5}
    }]
});

var Order = mongoose.model('Order', orderSchema);

invalid data:

{ user: '0123456789', lines: [] }

Error message:

{ message: 'Validation failed',
  name: 'ValidationError',
  errors:
   { user:
      { message: 'Path `user` is invalid (0123456789).',
        name: 'ValidatorError',
        path: 'user',
        type: 'regexp',
        value: '0123456789' } } }

I assume I misunderstand how this is supposed to work but i can't find the error.

Invalid data is definitely not stored in the database. Use the following test on your computer to make sure no document is saved by mongoose.

var mongoose = require('mongoose');
var assert = require('assert');
mongoose.connect('mongodb://localhost:27017/sotest');

var orderSchema = mongoose.Schema({
    user: {type: String, required: true, match: /^[a-zA-Z]{1,8}$/}, //\p{L}
    lines: [{
        name: String,
        count: {type: Number, required: true, min: 0, max: 5}
    }]
});

var Order = mongoose.model('Order', orderSchema);

var OrderItem = new Order({ user: '0123456789', lines: [] });
Order.collection.remove(function(err) {
    OrderItem.save(function (err) {
        if (err) {
            console.log(err);
        }
        Order.find({}, function(err, docs) {
            console.log(docs);
            assert(docs.length == 0, "No documents should be saved in the db!");
            Order.collection.remove(function(err) {});
        });
    });
});

If you can still see the data, it probably means that you didn't clear the content of the collection that the data is in.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM