MongoDB + Node.js:如何从一个外部文件使用架构为另一个架构?
我有一个类(或模型),需要使用另一个类作为其属性的一部分,如下所示。
**两个文件的标题**
var mongoose = require('mongoose'), Schema = mongoose.Schema;
item.js
module.exports = function() { var ItemSchema = new Schema({ name: String, cost: Number }); mongoose.model('Item', ItemSchema); }
receipt.js
ItemModel = require('./item.js'); var Item = mongoose.model('Item'); module.exports = function() { var LineItemSchema = new Schema({ item: Item, amount: Number }); var LineItem = mongoose.model('LineItem', LineItemSchema); var ReceiptSchema = new Schema({ name: String, items: [LineItemSchema] }); mongoose.model('Receipt', ReceiptSchema); }
在LineItem类中,我试图将variables'item'的types设置为类types,Item,node.js或mongoose.js正在尖叫着我,说有一个types错误。
如何从外部文件使用Schema“type”?
我不知道你为什么用匿名函数包装所有这些。 但是要从另一个模式引用模式,可以执行以下操作:
var LineItemSchema = new Schema({ item: { type: Schema.ObjectId, ref: 'Item' }, amount: Number });
当然你需要使用Schema对象:
var mongoose = require('mongoose'), Schema = mongoose.Schema;
在item.js
中,它从自执行函数返回模式。
module.exports = (function() { var ItemSchema = new Schema({ name: String, cost: Number }); mongoose.model('Item', ItemSchema); return ItemSchema; })();
然后在receipt.js
您现在可以像使用LineItemSchema一样使用模式。
var ItemSchema = require('./item.js'); // This should still create the model just fine. var Item = mongoose.model('Item'); module.exports = function() { var LineItemSchema = new Schema({ item: [ItemSchema], // This line now can use the exported schema. amount: Number }); var LineItem = mongoose.model('LineItem', LineItemSchema); var ReceiptSchema = new Schema({ name: String, items: [LineItemSchema] }); mongoose.model('Receipt', ReceiptSchema); }
这是所有的猜测和未经testing。