Mongoose: how to simulate a foreign key / feedback?

I use Mongoose to model collections Personand Transactionwhere each Transactionwill have references to two different instances Person:

var TransactionSchema = new Schema({
  , amount          : { type: Number, required: true }
  , from            : { type: ObjectId, required: true }
  , to              : { type: ObjectId, required: true }
  , date            : Date
});

var PersonSchema = new Schema({
    name            : { type: String, required: true }
  , transactions    : [ObjectId]
});

I would like everyone to Personhave a collection of everyone Transactionfor which they are either value toor fromfor. So far, this is the best way to find out how to do this:

TransactionSchema.pre('save', function(next, done) {
    var transaction = this;

    Person.findById(this.to, function (err, person) {
        person.transactions.push(transaction);
        person.save();
    });

    Person.findById(this.from, function (err, person) {
        person.transactions.push(transaction);
        person.save();
    });

    next();
});

It seems excessive. Is there a better way to do this, or am I trying to use MongoDB too much like a relational database? Instead of having a collection Transactionassociated with each instance Person, should I directly request a collection Translation?

Thank.

+5
1

, MongoDB.

. ?
, , , , ? ( , ?)
, , , , - :

var TransactionSchema = new Schema({
  , amount          : { type: Number, required: true }
  , from            : { 
     user_id: {
       type: ObjectId
     , required: true
    }
   , username: {
       type: String
     , required: true
    } 
  }
  , to              : { 
     user_id: {
       type: ObjectId
     , required: true
    }
   , username: {
       type: String
     , required: true
    } 
  }
  , date            : Date
});

, 3 , ( 2 ), .
, , , .

, , , ( , , ). ( , ):

TransactionSchema.pre('save', function(next, done) {
  var transaction = this;

  Person.where('_id').in([this.to, this.from]).run(function (err, people) {
    if (people.length != 2) { next(new Error("To or from doesn't exist")); return; }
    Step(
      function save_to() {
        people[0].transactions.push(transaction);
        people[0].save(this);
      },
      function save_from(err) {
        if (err) { next(err); return; }
        people[1].transactions.push(transaction);
        people[1].save(this);
      },
      function callback(err) {
        next(err); 
      }
    );
  });
});

Step , ( "" "from" ).

+7

All Articles