【发布时间】:2011-12-18 08:05:51
【问题描述】:
我正在使用 Mongoose 为 Person 和 Transaction 集合建模,其中每个 Transaction 将引用两个不同的 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]
});
我希望每个Person 都拥有一个集合所有Transactions,它们是to 或from 的值。到目前为止,这是我能够弄清楚如何做到这一点的最佳方法:
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();
});
这似乎太过分了。有没有更好的方法来做到这一点,或者我是否试图像使用关系数据库一样使用 MongoDB?我应该直接查询Translation 集合,而不是与每个Person 实例关联的Transactions 集合吗?
谢谢。
【问题讨论】: