我有一个类(或模型)需要使用另一个类作为其属性的一部分,如下所示。MongoDB + Node.js:如何从外部文件使用Schema来创建另一个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);
}
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类,我试图设置变量的项目类型'到类的类型,Item,node.js或mongoose.js正在尖叫我说它有一个类型错误。
如何从外部文件使用Schema“type”?
我也不确定,我在一些教程中看到它没有解释为什么。我是新来的这个express.js和mongoose.js的东西。我可以看到这是一个很好的解决方案,但我不明白为什么。是一个mongoosejs保留关键字。我认为类型可能也是如此。或者是ref只是程序员编写的一个变量?这是区分对象类型的唯一方法吗? – Vongdarakia
@ user3228667:是的,'type'和'ref'是“保留”关键字。你使用'ref'不是为了区分对象类型,而是参考其他模型。 – Amberlamps