samidarko samidarko - 1 year ago 90
Node.js Question

Creating a mongoose model containing array types return undefined for those in my docker container

I have a mongoose model containing 2 properties Array of String and some others:

var Model = new Schema({
_id: {type: Number, required: true, unique: true},
name: {type: String, required: true},
oneList: [String],
anotherList: [String]

I create the model:

var model = new Model({
_id: 1,
name: 'model',
oneList: ['a', 'b'],
anotherList: ['c', 'd']

but when I inspect the model all the list are undefined:

model._doc === {
_id: 1,
name: 'model',
oneList: undefined,
anotherList: undefined

I tried some variations:

  • change the model definition from [String] to [ ]

  • create separately the data outside the model then pass it

  • create the model without list data then add it to the model

Even when I create an empty model:

var model = new Model({})
model._doc.oneList === undefined
model._doc.anotherList === undefined

The problem occurs on a docker container but not on my local machine

node: v4.4.7

mongoose: v4.6.0


Answer Source

I had the same issue, apparently when you have a nested array within your model, mongoose has an open issue 1335 that saves an empty array when a property references a schema. I experimented with presaves to force the property to be an empty array if the property's length is 0 or undefined.

Also be careful when specifying unique=true in the property's schema, as empty or undefined properties will violate the indexing and throw an error.


var mongoose = require('mongoose');

var barSchema = new mongoose.Schema({
  baz: String

var fooSchema = new mongoose.Schema({
  bars: [barSchema]

var Foo = mongoose.model('Foo', fooSchema);

var foo = new Foo();
console.log(foo); // { _id: 55256e20e3c38434687034fb, bars: [] }, foo2) {
  console.log(foo2); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: [] }

  foo2.bars = undefined;, foo3) {
    console.log(foo3); // { __v: 0, _id: 55256e20e3c38434687034fb, bars: undefined }

    Foo.findOne({ _id: foo3._id }, function(err, foo4) {
      console.log(foo4); // { _id: 55256e20e3c38434687034fb, __v: 0, bars: [] }

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download