Change document after post-save middleware in mongoose

0

I'm working with mongoose.js and I'm going to need to, after saving the document in the database, I get 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 there is no point in running 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 registered in the 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 does not work. How to solve?

    
asked by anonymous 01.06.2017 / 20:37

1 answer

1

You can try to make a pre-update at the end of your document:

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

I hope it helps.

    
03.10.2017 / 02:07