I am trying to have an βoptionalβ subdocument in one of my models. Here is a sample diagram
var ThingSchema = mongoose.Schema({ name: String, info: { 'date' : { type: Date }, 'code' : { type: String }, 'details' : { type: Object } } }) var Thing = mongoose.model('Thing', ThingSchema);
In this case, I want the "info" property to be possibly null (optional), and will have application logic that checks if the information is null / undefined.
Unfortunately, even when the "info" property is undefined in a document in mongo, mongoose still returns me the object for the "info" field inside the extracted model.
For example, when I run this code, the "info" object is populated with a (empty) object.
var thingOne = new Thing({ name: "First Thing" }) thingOne.save(function(err, savedThing) { if (savedThing.info) { //This runs, even though the 'info' property //of the document in mongo is undefined console.log("Has info!"); } else console.log("No info!"); })
I tried to define ThingSchema as follows
var ThingSchema = mongoose.Schema({ name: String, info: { type: { 'date' : { type: Date }, 'code' : { type: String }, 'details' : { type: Object } }, required: false } })
Which allows me to get the undefined "info" property obtained from the database, but it allows me to break the "info" schema and add random properties, for example
savedThing.info.somePropertyThatDoesNotExistInTheSchema = "this shouldn't be here";
which will then be stored in the database. In addition, if the "info" property contains any additional attached documents, updating them does not mark the Thing model as dirty, which means that I have to manually mark the path as changed (via thing.markModified (path))
Is there a way to do what I'm trying to do? Are there any recommendations for this? Am I just using mongoose schemes wrong?
I need either
- Get the null "info" property for a Thing schema
- Is there a way to check if the "info" property is really null in mongo, although mongoose gives it a value when it is received.