2017-01-17 165 views
0

我正在嘗試將子文檔導入到我的Express/Mongoose API中。似乎無法導入子文檔

我有以下結構:

models 
     |-profile 
     | |-phones.js 
     | 
     |-profile.js 

這裏是phones.js模式文件:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var PhonesSchema = new mongoose.Schema({ 
    phone_number:{ type: String }, 
    phone_type:{ type: Number } 
}) 



module.exports = mongoose.model('PhonesSchema', PhonesSchema); 

這裏是profile.js父文檔,它駐留在模型文件夾:

var mongoose = require('mongoose'); 
var Schema = mongoose.Schema; 

var PhonesSchema = require('./profile/phones'); 

var ProfileSchema = new Schema({ 

    //PROFILE INFO 
    owner_id: { 
    type: String, 
    require: true, 
    unique: true 
    }, 
    linkedIn:{ 
    type: String 
    }, 
    phones:[PhonesSchema], 
}); 

module.exports = mongoose.model('Profile', ProfileSchema); 

但它不起作用。

任何想法?

+0

你能告訴我你的目錄結構? –

+0

爲什麼要在模式中定義模式?只需將你的孩子定義爲json對象... – LostJon

+0

@LostJon,我的理解是這是一個最佳實踐,因爲它更像是OOP方法,並且允許我在其他場景中導入和重用模式塊。我也認爲它提供了一種更簡潔的方法,可以讓這些細分市場的增長更容易管理代碼。你有什麼想法,這種方法有什麼缺點? – cnak2

回答

1

似乎問題更多的是因爲您導出PhonesSchema的模型而不是模式。除了使用

model.exports = mongoose.model('PhonesSchema',PhonesSchema) 

的,你應該使用:

model.exports = PhonesSchema 

裁判:https://mongoosejs.com/docs/subdocs.html