2014-06-23 40 views
1

我有一个类(或模型)需要使用另一个类作为其属性的一部分,如下所示。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”?

回答

2

我不知道为什么你将所有这些都包含在一个匿名函数中。但是,从另一个架构参考架构,你可以做到以下几点:

var LineItemSchema = new Schema({ 
    item: { 
     type: Schema.ObjectId, 
     ref: 'Item' 
    }, 
    amount: Number 
}); 

当然,你需要导入该架构对象:

var mongoose = require('mongoose'), 
Schema = mongoose.Schema; 
+0

我也不确定,我在一些教程中看到它没有解释为什么。我是新来的这个express.js和mongoose.js的东西。我可以看到这是一个很好的解决方案,但我不明白为什么。是一个mongoosejs保留关键字。我认为类型可能也是如此。或者是ref只是程序员编写的一个变量?这是区分对象类型的唯一方法吗? – Vongdarakia

+1

@ user3228667:是的,'type'和'ref'是“保留”关键字。你使用'ref'不是为了区分对象类型,而是参考其他模型。 – Amberlamps

0

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); 

} 

这是所有的猜测和未经测试。

+0

我也不清楚,我看到它在一些教程没有解释为什么。我是新来的这个express.js和mongoose.js的东西。 我看到你把方括号放在ItemSchema的周围。我在我的代码中通过在项目模式[Item]上放置方括号来尝试这一点,并且它工作正常。然而,当它不应该成为一个数组时,它不会是吗?我只是希望它是一个项目。 – Vongdarakia

+0

对不起,你是对的,方括号将使它成为这些模式项目的数组。 'item:ItemSchema'应该可以工作。我给出了我的答案,假设您希望将ItemSchema重用为多个其他模式,是否正确?如果你需要重用它们,分解多个js文件中的模式是合理的。 – Hayes

+0

我意识到当我说“我知道Item是一个模型而不是一个模式”时,我说的是错的。这是一个模式,并且与你的方式一样。但它不起作用。我收到一个类型错误。解决这个问题的唯一方法是使用Schema.ObjectId,它很广泛,因为它可以是任何东西。 – Vongdarakia

相关问题