Mongoose middleware Update or Save - node.js

I was wondering if I can do something like this in mongoose.
schema.pre('save' || 'update' , function (next) {
//do something
});
Like trigger this middleware either for save or update actions.
Thank you

No, as it will always result in the hook being made as a pre-save hook. Not because of Mongoose, but because of how ECMAScript logical operators work.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_Operators#Logical_OR
If you want a pre-save and a pre-validate hook, you would need to create them separately.

Related

Call instance Method inside Sub document mongoose hook

There are some fields in my Subdocument schema that I want to validate before saving to the database . However, if they are not valid, instead of failing, I just want to set them to undefined . I Defined the two functions on
ServerSchema.method
But when I try to access them in the hook, I get the error
this.conditionallyRemoveFields Is not a function
However, this only happens when saving the top level document, and is not when saving the server alone . When I save the server a loan, there are no errors . Here is the hook
ServerSchema.pre('save', function(next) {
this.conditionallyRemoveField(this.shouldRemoveField, ["Apple","orange"]);
next();
});
Any idea what might be going on ? Also, is this even the right approach for this problem ? Thanks in advance .
It turns out the solution was to define the methods before defining the parent schema. After doing that, everything worked perfectly.

Is it correct to change fields in pre('validate') middleware in mongoose?

I need to generate slug every time that post get saved into database. Specifficallly on Post.create and post.save. The single place where I may need this in PostShema.pre('validate') middleware like the following:
PostSchema.pre('validate', function (next) {
this.slug = sluglify(this.title);
return next();
});
All works fine except the fact that it happens in validate middlweare that should only check but not set.
SO my questuin is where should I reside my code for sluglify my title on creating or updating post?
This is not happening in the validation but before the validation. IMHO, it 's like if you are prepearing/cleaning your object before validating it; which is OK.
If you feel more confortable with that you could include it in a pre-save or pre-init instead of the pre-validate

mongoose pre update not firing

I have follow the directions in mongoose here
PostSchema.pre('update', function() {
console.log('pre update');
console.log(this);
});
it is not firing this middleware. Am I missing something here?
I have added next so it looks exactly like my pre save, however that still does nothing.
Make sure you don't define this after mongoose.model() has been called. Please also take note that findOneAndUpdate / upserts or updates won't trigger this hook. Another reason why it wouldn't execute is that validation fails. Therefore you would need to setup a pre('validate') hoke
I think you have to add the await keyword before your promise.

Extending MongoDB's "save" method in nodejs

In our app, we have a large document that is the source of most of our data for our REST api.
In order to properly invalidate our client-side cache for the REST api, i want to keep track of any modifications made to teh document. The best we came up with is to extend the mongo save command for the document to send off the notification (and then save as usual).
The question is, how does one actually do this in practice? Is there a direct way to extend mongo's "save" method, or should we create a custom method (i.e. "saveAndNotify") on the model that we use instead (which i would avoid if i can)?
[edit]
So in principle, i am looking to do this, but am having an issue not clobbering the parent save function();
mySchema.methods.save = function() {
// notify some stuff
...
//call mongo save function
return this.super.save();
};
Monkey patching the core mongo object is a bad idea, however it turns out mogoose has a middleware concept that will handle this just fine:
var schema = new Schema(..);
schema.pre('save', function (next) {
// do stuff
next();
});

Mongoose Model.count() does not run callback as documented

I am following almost the exact example for Model.count() from the Mongoose docs:
User.count({ type: 'jungle' }, function (err, count) {
console.log('I do not ever run');
});
This should print 'I do not ever run'. Instead, it returns a Query object - which should not happen, according to the docs, as I am providing a callback. How can I make the callback function run? Is there some circumstances where the callback is not run?
Using mongoose#3.6.17. Thanks!
Make sure you've connected to the database before calling any model functions. Mongoose will just queue up the count query until you connect otherwise.
See this question of the FAQ.

Resources