How to update model in mongoose pre-save from async result?

883 Views Asked by At

below are two pre-save hooks. I can't get mongoose to update the model based on the result of an async call to another DB. On save, I'd like to run the neo query, then store the result in the Mongoose model.

In both cases, all nodes have neoId===999

schema.pre('save', function(next) {
  var self = this;
  this.neoId = 999;
  // Save the topic
  neo.query('MERGE (t:Topic { title: {title}, aliases: {aliases}, type: {type}, mongoId: {_id} }) RETURN id(t);', this, function(err, data) {
    self.neoId = data;
    console.log(self);
    next(err); });
});

Aysnc:

schema.pre('save', true, function(next, done) {
  var self = this;
  this.neoId = 999;
  // Save the topic
  neo.query('MERGE (t:Topic { title: {title}, aliases: {aliases}, type: {type}, mongoId: {_id} }) RETURN id(t);', this, function(err, data) {
    self.neoId = data;
    console.log(self);
    next(err);
    done(err);
  });
});
1

There are 1 best solutions below

0
On BEST ANSWER

I was assigning self.neoId to an array. For some reason, it kept the 999 value instead of erroring. Anyways, this worked:

schema.pre('save', function(next) {
  var self = this;
  // Save the topic
  neo.query('MERGE (t:Topic { title: {title}, aliases: {aliases}, type: {type}, mongoId: {_id} }) RETURN id(t) as id;', this, function(err, data) {
    self.neoId = data['id'];
    next(err);
  });
});