Change document after post-save middleware in Mongoose

Asked

Viewed 83 times

0

I’m working with the Mongoose.js And I’m going to need, after I save the document to the database, to be able to change an attribute of that document. From what I understood in the Mongoose documentation itself, I realized that I could do this using a middleware in the schema.

NOTE: I need to define this directly in my schema, because this manipulation is part of the business rule of the application so it is POINTLESS to execute 2 queries to the database.

See the example below:

var mongoose = require('mongoose');

// schema exemplo
var FooSchema = new mongoose.Schema({
    foo: string,
    bar: string
});

// middleware exemplo
FooSchema.post('save', function(doc){
    doc.update({ _id: doc._id}, { $set: { bar:'bar'} }, function(err){
        console.log(err);
    });
});

// criando a coleção na base de dados
var FooModel = mongoose.model('Foo', FooSchema, 'Foo');

// salvando um documento de exemplo
var teste = new FooModel({foo:'foo', bar:'foo'});
teste.save();

What I need to do is that after the document is saved in the database, I can manipulate data directly by the business rule already recorded in middleware.

This will be used for data Mining, so in certain cases there are treatments that must be done...

Is there any way to manipulate the document after saving it, through a middleware? Theoretically the above code allows me to do this, but it doesn’t work. How to solve?

1 answer

1


Voce can try to do a pre update at the end of your document:

FooSchema.pre('update', function() {  
     this.update({ _id: this._id},{$set: { bar:'bar'} });
});

hope it helps.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.