Mongoose: Schema, array, default value (default value "[]" is not working)

Created on 15 Feb 2011  ·  6Comments  ·  Source: Automattic/mongoose

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
console.log(arrayTestSchema.anArray);

mongoose.connection.close();

displays "undefined"

Most helpful comment

It's failing because you're not accessing your document instance. I've commented out your console.log and replaced it with the correct one.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
// console.log(arrayTestSchema.anArray);
console.log(myTest.anArray);

mongoose.connection.close();

All 6 comments

At least in master, this works fine for me.. except it returns a MongooseArray so it's full of lots of other craziness :) Not just the value.

What version are you running?

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({

 Title: String,
 Description: String,
 Status: String

});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();

myTest.Title = 'Project';
myTest.Description = 'using mongodb & node';
myTest.Status = 'open';

console.log(myTest);

mongoose.connection.close();

I'm running 1.0.12, npm version.
Should be the master version as I see that the 1.0.12 was released yesterday.

Don't understant what you want to point out pradeepthundiyil.

It's failing because you're not accessing your document instance. I've commented out your console.log and replaced it with the correct one.

var mongoose = require('mongoose');
var Schema = mongoose.Schema;

mongoose.connect('mongodb://localhost/dbTest');

var arrayTestSchema = new Schema({
    anArray: {
      type: Array,
      'default': []
    }
});

mongoose.model('ArrayTest', arrayTestSchema);
ArrayTest = mongoose.model('ArrayTest');

var myTest = new ArrayTest();
// console.log(arrayTestSchema.anArray);
console.log(myTest.anArray);

mongoose.connection.close();

lol, ok i see, yesterday was a bad day for me. Thanks for pointing this out =)

@bnoguchi what about the type of array items?

Was this page helpful?
0 / 5 - 0 ratings