Friday 2 June 2017

Mongo / Mongoose: schema.post('save', (doc) => {}) not sending doc

I'm trying to implement some post-save callbacks in mongoose@4.9.2, but I'm not seeing a document sent to the post save callback as the documentation suggests. The documentation says One should be able to do:

schema.post('save', function(doc) {
  console.log('%s has been saved', doc._id);
});

However, when I try the same, doc seems like a mongo connection:

schema.post('update', (doc) => {
  console.log(doc._id, doc);
  doc.location = {
    'type': 'Point',
    'coordinates': [doc.longitude, doc.latitude]
  }
});

This console logs:

undefined CommandResult {
  result: { n: 1, nModified: 1, ok: 1 },
  connection:
   Connection {
     domain: null,
     _events:
     // lots of other jibber jabber

What am I missing? Here's my full model definition:

var mongoose = require('mongoose')
var autoIncrement = require('mongoose-auto-increment')
var mongoosePaginate = require('mongoose-paginate')
var _ = require('lodash')
mongoose.Promise = require('bluebird')

// config
var table = 'building'
var db = require('../db')
var config = require('../../../config')
var capitalized = _.startCase(_.toLower(table))
var schema = new mongoose.Schema(db[table])

// autoincrement a new Id field and add pagination
autoIncrement.initialize(mongoose.createConnection('mongodb://localhost/' + config.db));
schema.plugin(autoIncrement.plugin, {model: capitalized, field: table + 'Id'});
schema.plugin(mongoosePaginate);

schema.post('update', (doc) => {
  console.log(doc._id, doc);
  doc.location = {
    'type': 'Point',
    'coordinates': [doc.longitude, doc.latitude]
  }
});

module.exports = mongoose.model(capitalized, schema, table + 's');

Any help others can offer would be very welcome!



via duhaime

No comments:

Post a Comment