Does mongoose have an audit check?

I have a mongoose setting that includes an inline scheme, say: Blogpost with inline comments. Comments can be edited by the original publisher as well as by the editor / administrator. After adding / editing a comment, the entire blog post is saved.

I have the usual mongoose 'pre' middleware installed on the built-in comment scheme, which automatically sets lasteditdate for this particular comment.

The fact is that "pre" is called in EVERY blog comment since I call save () on blogpost. (For other reasons, I need to do it like this). So I need to check which comments have been changed (or are new) since they were last saved (as part of the general save ()) Blogpost

Questo: how to check "pre", has the comment changed or not? Obviously, calling this.isNew not enough, as comments can be edited (i.e. are not new).

Is there isDirty or similar that I am missing?

+4
source share
3 answers

You can use a modified getter:

 if (doc.modified) { // :) } 
+3
source

For version 3.x

 if(doc.isModified()){ // do stuff } 
+16
source

In Mongoose, you can use the Document isModified(@STRING) method.

The latest documentation for the method can be found here .

So, to check for a specific property with doc.isModified, you can do this:

 doc.comments[4].message = "Hi, I've made an edit to my post"; // inside pre hook if ( this.isModified('comments') ) { // do something } 

If you want to check for a specific comment, you can do this with the following entry this.isModified('comments.0.message')

Since the argument takes a string, if you needed to know exactly which comment was changed, you can scroll through each comment and run this.isModified('comments['+i+']message')

+5
source

Source: https://habr.com/ru/post/1210354/


All Articles