两个Mongoose模型中的循环依赖

时间:2016-01-08 14:15:25

标签: node.js mongodb mongoose

我有一个循环依赖问题,有两个相互依赖的mongoose模式。代码如下:

// user.model.js
var mongoose = require('mongoose');
var transactionSchema = mongoose.model('Transaction').schema;

var userSchema = mongoose.Schema ({
  name : String,
  wallet: Number,
  transactions: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Transaction'} ]
});

var User = mongoose.model('User', userSchema);

// transaction.model.js
var mongoose = require('mongoose');
var userSchema = mongoose.model('User').schema;

var transactionSchema = mongoose.Schema ({
  sourceUser: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  targetUser: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  amount: Number,
  status: String
});

var Transaction = mongoose.model('Transaction', transactionSchema);

如此加载:

// app.js
 var mongoose = require('mongoose');

require('./models/user.model');
require('./models/transaction.model');

问题很明显但不清楚如何解决。

1 个答案:

答案 0 :(得分:-1)

user.model.js

var mongoose = require('mongoose');

var userSchema = mongoose.Schema ({
  name : String,
  wallet: Number,
  transactions: [ {type: mongoose.Schema.Types.ObjectId, ref: 'Transaction'} ]
});

var User = mongoose.model('User', userSchema);

transaction.model.js

var mongoose = require('mongoose');

var transactionSchema = mongoose.Schema ({
  sourceUser: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  targetUser: {type: mongoose.Schema.Types.ObjectId, ref: 'User'},
  amount: Number,
  status: String
});

var Transaction = mongoose.model('Transaction', transactionSchema);