Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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 }, '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?

like image 768
Karolis Juodelė Avatar asked Jul 13 '14 10:07

Karolis Juodelė


1 Answers

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.

like image 81
JohnnyHK Avatar answered Oct 11 '22 00:10

JohnnyHK