node.jsmongodbmongoose

$unset is not working in mongoose


My schema is as follows : -

var Schema1 = new mongoose.Schema({
  name: String,
  description: String,
  version: [{
    id: String,
    status: Number
 }]
});

I want to unset the version field. I try the following code :-

Schema1.update({}, {
 $unset: {
  version: 1
  }
 }, {
 multi: true
}).exec(function(err, count) {
 console.log(err, count)
});

It gives me the following output :-

null 10

But the output contain the version field :-

{
  name : 'a',
  description : 'sdmhf',
  version : []
}

The above code remove the data but I want to remove the version field from my collection as well. Can you tell me how to do that?


Solution

  • There's nothing wrong with your code. Mongoose is actually deleting those fields in the documents (which I assume is what you expected). You can see by opening a mongo shell into your database and searching all your documents before and after the update (use db.yourcollection.find({}))

    Why does an empty array still appear even when it's removed from every document in the collection? Mongoose will ensure the documents returned will obey the schema that you define. So even if Mongoose finds no version property pointing to an Array in the actual document, it will still present an empty array when the matching documents are returned.

    You can verify this yourself by adding some arbitrary property (pointing to an Array) to your schema and running a .find({}) again. You'll see that Mongoose will return these properties in every document even though you never saved them to the database. Similarly, if you add non-Array properties like Strings, Booleans, etc, Mongoose will return those as long as you specify a default value.

    If you want to drop version for good (as you mentioned in your comment) you can drop it from your Mongoose schema after you've completed the $unset.