zedjay72
zedjay72

Reputation: 177

Why does Mongoose hide my field?

Mongoose seems to be hiding my timestamp field when I'm setting it in a pre 'save' hook. Any idea why?

I have this Schema:

var dpsSchema = new Schema({
    timestamp: Date,
    _loaded_schedules: [{type: Number, ref: 'prun_schedules'}]
})

dpsSchema.pre('save', function(next){
    this.timestamp = new Date();
    next();
})

and I run this code:

var Dpm_model = mongoose.model('daily_production_meta', dpm_schema);

var pm = new Dpm_model();
pm.save();

setTimeout(console.log(pm), 2000);

The resulting console log looks like this:

{ _id: 5871410c08b91cfd82124656,
  _loaded_schedules: [] }

But when I log into mongodb via terminal and check that document, I see the timestamp field!

How come?

Upvotes: 0

Views: 60

Answers (1)

Alex
Alex

Reputation: 38519

The problem is with your call to

pm.save();

This is an async call, expecting a callback.

Change this to

pm.save(function(err){ 
    setTimeout(function(){console.log(pm)}, 2000);
});

and it should work as expected.

Upvotes: 1

Related Questions