Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

does mongoose have an isDirty check?

I have a mongoose setup which involves an embedded-schema, lets say: A Blogpost with embedded comments. Comments can be edited by the original publisher as well as by an editor/admin. After adding / editing a comment the entire blogpost is saved.

I have some custom mongoose's 'pre' middleware set up on the embedded comment-schema which automatically sets the lasteditdate for that particular comment.

The thing is that 'pre' is called on EVERY comment on the blogpost, since I call save() on the blogpost. (For other reasons I need to do it like this) . Therefore, I need a way to check which comments have changed (or are new) since they were last saved (as part of the Blogpost overall save())

The questio: how to check in 'pre' whether a comment has changed or not? Obviously calling this.isNew isn't sufficient, since comments could be edited (i.e: aren't new) as well.

Is there any isDirty or similar that I'm overlooking?

like image 794
Geert-Jan Avatar asked Nov 28 '22 14:11

Geert-Jan


2 Answers

For version 3.x

if(doc.isModified()){
  // do stuff
}
like image 51
elisa.zc Avatar answered Nov 30 '22 04:11

elisa.zc


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

The most recent documentation for the method can be found here.

So to check 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 a specific comment you can do that with the following notation this.isModified('comments.0.message')

Since the argument takes a string if you needed to know specifically which comment was modified you could loop through each comment and run this.isModified('comments['+i+']message')

like image 22
SStanley Avatar answered Nov 30 '22 03:11

SStanley