Saturday 1 April 2017

Why does invoking toObject() on a mongoose document delete a property when called with getters set to true?

When invoking toObject() on a document with a (nested) property which is set to null, the property will be erased but only when supplying the getters option with true, see example below.

var mongoose = require('mongoose');

const schema = new mongoose.Schema({
   customer: {
      name: { type: String, required: false },
   },
});

var Model = mongoose.model('Model', schema);
var model = new Model();
model.customer = null;
console.log(model.toObject());
console.log(model.toObject({ getter: true }));

//Prints: 
//{ _id: 58e00dcd71bf5916802bdb3c, customer: null }
//{ _id: 58e00dcd71bf5916802bdb3c, id: '58e00dcd71bf5916802bdb3c' }

Why is this?



via Christian

No comments:

Post a Comment