Karolis JuodelÄ— Karolis JuodelÄ— - 1 year ago 102
Node.js Question

Undefined model fields with `strict: false`

var mongoose = require('mongoose');
mongoose.connect('mongodb://localhost/test', {user: 'mongod'});
mongoose.connection.once('open', function () {

I create a model with one field and strict: false

var Foo = mongoose.model('Foo', mongoose.Schema({
foo: String
}, {strict: false}));

Then save a model with two fields

Foo.create({foo: "FOO", bar: "BAR"}, function () {

Then read it and print it with its fields

Foo.findOne(function (err, f) {
console.log(f, f.foo, f.bar);


The output is
{ foo: 'FOO', bar: 'BAR', _id: 53c249e876be58931f760e70, __v: 0 }
. The new element is correctly saved and
can see
, but I can't. As soon as I add bar to the schema, I can see it too. Is this intended behavior? How can I reach
without including it in the schema?

Answer Source

You can access fields not defined in your schema with get:

Foo.findOne(function (err, doc) {
  console.log(doc, doc.foo, doc.get('bar'));


{ _id: 53c28dad3b2464566cf5672d, foo: 'FOO', bar: 'BAR' } 'FOO' 'BAR'

The bar field also shows up when logging doc as the inspect method of a Mongoose document outputs all fields.