1

Here and here is solution for unsetting some fields which works fine unless they are nested. When I tried the following thing 'null' is being saved against the field instead of unsetting it. How can I get it working ?

PostSchema = new Schema({
title : String
, slug : String
, publish : {
    done : {type:Boolean, default:false}
    , on : Date
    , by : ObjectId
  }
, created : Date
, ...
});


PostSchema.pre('save', function(next) {

if(!this.isNew && this.isModified('publish') && !this.publish.done) {
 //console.log('OK I am going to unset publish.on, publish.by ');
 this.publish.on = undefined;
 this.publish.by = undefined;
}

// do some other stuffs
next();

});

EDIT

I got following log :

Mongoose: posts.update({ _id: ObjectId("53e3695289469b7136000033") }) { '$set': { lastModifiedOn: new Date("Fri, 08 Aug 2014 06:47:06 GMT"), publish: { done: false, on: undefined, by: undefined } } } {}

Community
  • 1
  • 1
Lekhnath
  • 4,532
  • 6
  • 36
  • 62
  • How are you `saving` the document? Are you using `.save()` or `update` ? – ma08 Aug 08 '14 at 06:36
  • `.save()` of course to be able to hooked on the `pre('save')` hook. – Lekhnath Aug 08 '14 at 06:38
  • just making sure, your code seems to be ok. I don't see any reason why it shouldn't work. Can you set the option `mongoose.set('degbug', true)` and post the output of the console when the query is called? – ma08 Aug 08 '14 at 06:41
  • Yes please. I have edited my question with the logged output. – Lekhnath Aug 08 '14 at 06:55
  • It should look like this `'$unset': { 'publish.by': 1, 'publish.on': 1 }`. What version of mongoose and mongodb are you using? – ma08 Aug 08 '14 at 06:57
  • I am currently using `{"mongodb" : "2.4.10", "mongoose": "3.8.1"}` – Lekhnath Aug 08 '14 at 07:01
  • 1
    I can't replicate the problem using mongodb:2.6.3 and mongoose:3.8.9. I don't think it's anything version related. But it sure looks weird, maybe the issue is with some code which you haven't given here. – ma08 Aug 08 '14 at 07:48
  • It, works fine with mongodb: 2.4.6, mongoose: 3.8.14. – Foad Nosrati Habibi Aug 08 '14 at 10:23

0 Answers0