2014-06-23 38 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

相關問題