Undefined model fields with `strict: false`
mongodb, mongoose, node.js
Solution
You can access fields not defined in your schema with `get`:
Foo.findOne(function (err, doc) {
console.log(doc, doc.foo, doc.get('bar'));
});
output:
{ _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.
Problem
``` 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 }`, `'FOO'`, `undefined`. The new element is correctly saved and `console.log` can see `'BAR'`, 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 `bar` without including it in the schema?