node.js - How do I use a pre save hook database value in Mongoose? -
i want value of object before pre-save hook , compare new value. suggested in mongoose db value in pre-save hook , https://github.com/automattic/mongoose/issues/2952, did post-init hook copied doc._original. issue i'm not sure how access ._original in different hook.
fieldschema .post('save', function (doc) { console.log(doc._original); }); fieldschema .post('init', function (doc) { doc._original = doc.toobject(); });
i know doc in post save hook different doc in post init hook, how access original?
you can access properties on database have defined in schema. since haven't defined _original
property in schema, can't access, or set it.
one way define _original
in schema.
but , set properties not defined in schema: use .get
, , .set
{strict:false}
fieldschema .post('save', function (doc) { console.log(doc.get('_original')); }); fieldschema .post('init', function (doc) { doc.set('_original', doc.toobject(), {strict: false}); });
note option {strict: false}
passed .set
required because you're setting property not defined in schema.
update:
first thing didn't notice before in question title want pre-save hook in code have post-save hook (which based answer on). hope know you're doing, in post save hook invoked after saving document.
but in opinion, , can understand original intent question, think should use pre-save hook , async version of (by passing next
callback), can .find
(retrieve) document database, original version since new version hasn't yet been saved (pre-save) enabling compare without saving new fields, seems anti-pattern begin with.
so like:
fieldschema .pre('save', function (next) { var new_doc = this; this.constructor // ≈ mongoose.model('…', fieldschema).findbyid .findbyid(this.id, function(err, original){ console.log(original); console.log(new_doc); next(); }); });
Comments
Post a Comment