SSH This SSH This - 1 year ago 98
Node.js Question

Missing Mongoose Schema Property Still Being Returned

Given a schema that looks like this:

var schema = new mongoose.Schema({ name: 'string', size: 'string' });


And the database contains "name" for all objects in the collection. But then I change it and remove name

var schema = new mongoose.Schema({ size: 'string' });


And then I do a find on it:

schema.find({}).exec().then( (objs) => {
// objs[0].name still exists


I thought that if the schema didn't specify a property then it wouldn't exist on the found objects. Is this not the case? Is the only way to remove a property, to actually remove it from the object in mongo?

Answer Source

Quoting from the original maintainer, Aaron Heckmann:

[M]ongoose "plays nice" with existing data in the db, not deleting it unless you tell it to.

[D]eleting the property would work if mongoose was able to hook into that even but alas it cannot. [H]owever you can completely remove the property from your document by setting the values to undefined which will trigger an $unset.

Source: Google Groups

Basically Mongoose attempts to be non-destructive to existing data. If a property is no longer needed you could run an update on the database to unset the value which would remove the property from every document in the collection.

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download