Shane Davies
Shane Davies

Reputation: 970

How do I find missing schema fields on a Mongoose query

If I add new fields directly to my MongoDB database and I forget to add them to my Mongoose schema, how can I alert myself to the problem without it failing silently.

The following example shows that all fields are returned from a query (regardless of the schema) but undefined if you access the key.

var mongoose = require('mongoose');

var user_conn = mongoose.createConnection('mongodb://db/user');
var userSchema = mongoose.Schema({
  email: String,
  // location: String,
  admin: Boolean
});
var User = user_conn.model('User', userSchema);

User.findOne({email: '[email protected]'}, function (err, doc) {
  if (err) return console.log(err);
  console.log(doc);
  console.log(doc.email);
  console.log(doc.location);
});

Result:

{ _id: 57ce17800c6b25d4139d1f95,
  email: '[email protected]',
  location: 'Australia',
  admin: true,
  __v: 0 }      // <-- console.log(doc);

[email protected]  // <-- console.log(doc.email);

undefined       // <-- console.log(doc.location);

I could read each doc key and throw an error if undefined, but is this the only way?

Versions Node.js: 6.5.0 Mongoose: 4.6.0

Upvotes: 1

Views: 2144

Answers (2)

Shane Davies
Shane Davies

Reputation: 970

Following on from Amiram's answer. I now use lean() to get the object during a query but when I need to update or save it still looks up the schema.

User.findOne({email: '[email protected]'}).lean().exec(function (err, doc) {
  console.log(doc);
  console.log(doc.email);
  console.log(doc.location);
});

Upvotes: 2

Amiram Korach
Amiram Korach

Reputation: 13296

You can set strict to false on the schema so it will save all properties even if they are not in schema:

var userSchema = mongoose.Schema({
  email: String,
  admin: Boolean
}, {strict: false});

http://mongoosejs.com/docs/guide.html#strict

In order to get a property which is not in schema you need to use doc.toObject() and use the returned object, or to use doc.get('location')

Upvotes: 3

Related Questions