0

There is a one to many relationship between schemaA and schemaB. If I call schemaA.remove(); I want all related schemaB to be removed. If I call schemaB.remove() I want the reference to schemaB in instanceA to be removed.

Using

SchemaA
  .pre('remove', function (next) {
    var instanceBIdArray = this.instanceBIdArray;

    async.map(instanceBIdArray, function (instanceBId, callback) {
        SchemaB.findByIdAndRemove(instanceBId, function (err, instanceB) {
          if (err) callback(err);
          if (!instanceB) callback('instanceB not found.');
          callback(null, instanceBId);
        });
      },
      function (err, results) {
        if (err) next(new Error('Something went wrong with deleting instanceB.'));
        return next();
      });
  });

And

SchemaB
  .pre('remove', function (next) {
    var self = this;
    SchemaA.findByIdAndUpdate(self.instanceAId, {
      $pull: {
        instanceBIdArray: self._id
      }
    }, function (err, instanceA) {
      if (err) next(new Error('Something went wrong with deleting instanceA.'));
      return next();
    });
  });

in each of the mongoose schemas respectively seems to be the right way to approach this. However, I can only get one of the two to work. If I have both express will not compile, and it will say that schemaB does not exist.

I believe this has something to do with require.js and that in order to export schemaA requirejs needs to export schemaB and vice versa. Any insight to this is greatly appreciated!

The error is: MissingSchemaError: Schema hasn't been registered for model "A".

Ouwen Huang
  • 1,037
  • 2
  • 9
  • 25
  • What's your actual code? (in place of the pseudo code) – laggingreflex Jan 10 '15 at 13:31
  • Sounds like you have a dependency cycle in your code; see [this question](http://stackoverflow.com/questions/10869276/how-to-deal-with-cyclic-dependencies-in-node-js) for ideas on how to deal with it. – JohnnyHK Jan 10 '15 at 14:31
  • I've been attempting these solutions, but since mongoose needs to compile the Schemas in the end it keeps giving me the MissingSchemaError – Ouwen Huang Jan 10 '15 at 19:25
  • Even if I put these schemas in the same JS file, I don't think I can compile both mongoose schemas... – Ouwen Huang Jan 10 '15 at 19:36
  • 1
    Instead of using the schema variable, use `mongoose.model('A').findByIdAndUpdate`, where `A` is the model name associated to `SchemaA`. As long as both models have been registered before you attempt to save one of the documents it will work. – Brian Shamblen Jan 12 '15 at 17:10
  • Ah that seems like a good solution I'll give it a try! – Ouwen Huang Jan 12 '15 at 17:16
  • Hey I just tried out this solution and it works very nicely. Thank you @BrianShamblen – Ouwen Huang Jan 13 '15 at 01:03

0 Answers0