简体   繁体   中英

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: 'foo@bar.com.au'}, function (err, doc) {
  if (err) return console.log(err);
  console.log(doc);
  console.log(doc.email);
  console.log(doc.location);
});

Result:

{ _id: 57ce17800c6b25d4139d1f95,
  email: 'foo@bar.com.au',
  location: 'Australia',
  admin: true,
  __v: 0 }      // <-- console.log(doc);

foo@bar.com.au  // <-- 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

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')

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: 'foo@bar.com.au'}).lean().exec(function (err, doc) {
  console.log(doc);
  console.log(doc.email);
  console.log(doc.location);
});

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM