1

I have a Food schema with a required field name. For some reason, when I try to create a food item with the create function (below), it throws a ValidationError: Path 'name' is required, even though my object does indeed have a name field:

Food.create({
    name: "milk",
    daysUntilExpiration: 5
});

My mongoose debug output also shows that it's performing an insert, and the object being saved has the name field:

Mongoose: foods.insert({ name: 'milk', daysUntilExpiration: 5, _id: ObjectId("59608100cb0578165dd35de9"), __v: 0 })

On the other hand, if I create a new object and then save, it works as expected:

f = new Food({ name: "milk", daysUntilExpiration: 5 });
f.save() // no validation error!

Why is this behavior different? I was under the impression that the difference between create and new/save was purely for programming convenience (e.g. wanting to work with an object after you create it but before you save to the DB), but it seems like I'm mistaken.

EDIT: Stack trace of the validation error:

ValidationError: Food validation failed: name: Path `name` is required.
        at ValidationError.inspect (/Users/jess/herb/node_modules/mongoose/lib/error/validation.js:63:24)
        at formatValue (util.js:352:36)
        at inspect (util.js:186:10)
        at exports.format (util.js:72:24)
        at Console.log (console.js:43:37)
        at tryCatcher (/Users/jess/herb/node_modules/bluebird/js/main/util.js:26:23)
        at Promise._settlePromiseFromHandler (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:507:31)
        at Promise._settlePromiseAt (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:581:18)
        at Promise._settlePromises (/Users/jess/herb/node_modules/bluebird/js/main/promise.js:697:14)
        at Async._drainQueue (/Users/jess/herb/node_modules/bluebird/js/main/async.js:123:16)
        at Async._drainQueues (/Users/jess/herb/node_modules/bluebird/js/main/async.js:133:10)
        at Immediate.Async.drainQueues (/Users/jess/herb/node_modules/bluebird/js/main/async.js:15:14)
        at runCallback (timers.js:651:20)
        at tryOnImmediate (timers.js:624:5)
        at processImmediate [as _immediateCallback] (timers.js:596:5) 

errors:
    { name:
      { MongooseError: Path `name` is required.
          at ValidatorError (/Users/jess/herb/node_modules/mongoose/lib/error/validator.js:24:11)
          at validate (/Users/jess/herb/node_modules/mongoose/lib/schematype.js:744:13)
          at /Users/jess/herb/node_modules/mongoose/lib/schematype.js:790:11
          at Array.forEach (native)
          at SchemaString.SchemaType.doValidate (/Users/jess/herb/node_modules/mongoose/lib/schematype.js:750:19)
          at /Users/jess/herb/node_modules/mongoose/lib/document.js:1462:9
          at _combinedTickCallback (internal/process/next_tick.js:67:7)
          at process._tickCallback (internal/process/next_tick.js:98:9)
        message: 'Path `name` is required.',
        name: 'ValidatorError',
        properties: [Object],
        kind: 'required',
        path: 'name',
        value: undefined,
        reason: undefined } },
  _message: 'Food validation failed',
  name: 'ValidationError' }

EDIT 2: Food schema:

var mongoose = require('mongoose');

var schema = new mongoose.Schema({
    name: {
        type: String,
        required: true,
        min: 1,
        max: 100
    },

    daysUntilExpiration: {
        type: Number,
        min: 0
    }
});

module.exports = mongoose.model('Food', schema);
Jess
  • 1,515
  • 3
  • 23
  • 32
  • How can it _both_ throw an error _and_ insert a document? – robertklep Jul 08 '17 at 07:16
  • @robertklep Exactly what I'm wondering! – Jess Jul 08 '17 at 07:21
  • A plausible explanation for that though: Mongoose logging might happen before the insert actually succeeds. – Jess Jul 08 '17 at 07:25
  • it's Mongoose that performs the validation, not MongoDB itself, so Mongoose would throw the error before even considering inserting something. I think the error is actually thrown somewhere else. The stack trace that accompanies it may provide some clues. – robertklep Jul 08 '17 at 07:26
  • Can you also include your schema and any other pre save hooks/ validations you have defined ? – Talha Awan Jul 08 '17 at 07:34
  • @Jess _"FoodItem validation failed"_. That sounds like a different model? The stack trace itself doesn't provide a clue what the root location of the error is, sadly. – robertklep Jul 08 '17 at 07:35
  • Oops, I pasted a old chunk of output. I renamed the model since then, still the same error. – Jess Jul 08 '17 at 07:40
  • @TalhaAwan edited with schema, it's almost stupidly simple -- I don't have any other pre save hooks/validations of my own. – Jess Jul 08 '17 at 07:42
  • @Jess `create` working with me without error. Can't see what the problem is. Do you have FoodItem schema as well? – Talha Awan Jul 08 '17 at 07:45
  • No, i renamed FoodItem to Food. I feel like create should generally work, too, but I'm not sure why this specific instance fails... – Jess Jul 08 '17 at 07:49
  • @Jess it's not re-createable (either by Talha or by me), so it must be something in your app that's causing it. Are you using Mongoose plugins? – robertklep Jul 08 '17 at 09:41

0 Answers0