2016-01-24 22 views
0

我試圖populate Mongoose模式內的一個屬性,該屬性引用另一個外部模型/模式中的屬性。使用外部文件中的模型填充Mongoose模式屬性

我能得到貓鼬人口/引用工作時,兩個模型/架構和查詢都在同一個文件,但我有我的架構設定這樣的車型都在自己的文件/模型內目錄中,而/models/index.js將返回的模型對象(顯然index.js知道要排除自身)

我運行到這個問題,是因爲該架構/模型是都在他們自己的文件中,當我指定模型名稱作爲參考時,它不起作用。我嘗試在另一個模型中加載特定的模型本身,但也失敗了。

FYI:IM相當新的MongoDB和貓鼬,所以下面的代碼是非常非常粗糙的,它主要是我在學習

組模式

// models/group.js 
'use strict' 

module.exports = Mongoose => { 
    const Schema = Mongoose.Schema 

    const modelSchema = new Schema({ 
     name: { 
      type: String, 
      required: true, 
      unique: true 
     } 
    }) 

    return Mongoose.model(ModelUtils.getModelName(), modelSchema) 
} 

的過程賬戶型號

// models/account.js 
'use strict' 

module.exports = Mongoose => { 
    // I tried loading the specific model being referenced, but that doesn't work 
    const Group = require('./group')(Mongoose) 
    const Schema = Mongoose.Schema 

    const modelSchema = new Schema({ 
     username: { 
      type: String, 
      required: true, 
      unique: true 
     }, 
     _groups: [{ 
      type: Schema.Types.ObjectId, 
      ref: 'Group' 
     }] 
    }) 

    // Trying to create a static method that will just return a 
    // queried username, with its associated groups 
    modelSchema.statics.findByUsername = function(username, cb) { 
     return this 
      .findOne({ username : new RegExp(username, 'i') }) 
      .populate('_groups').exec(cb) 
    } 

    return Mongoose.model(ModelUtils.getModelName(), modelSchema) 
} 

正如你可以在帳戶模型看,我試着去引用組模型作爲_groups元素,然後查詢帳戶在填充modelSchema.statics.findByUsername靜態方法裏面的相關聯基團..

主應用程序文件

// app.js 
const models = require('./models')(Mongoose) 

models.Account.findByUsername('jdoe', (err, result) => { 
    console.log('result',result) 

    Mongoose.connection.close() 
}) 
+1

爲什麼你需要在賬戶模型中設置組模型?看看給定的代碼,這似乎不是必要的。 'ModelUtils'的目的是什麼? – qqilihq

+0

我實際上已經在本地註釋掉了,這是拋出錯誤。我猜測**可能是賬戶模式需要它,因爲它被引用,但那只是在黑暗中拍攝的。 – Justin

回答

1

我不清楚如何ModelUtils.getModelName()實現。我認爲這個問題應該在這裏,因爲它在我改變你的代碼後效果很好,如下所示

// group.js 
return Mongoose.model('Group', modelSchema); 

// account.js 
return Mongoose.model('Account', modelSchema); 

// app.js 
const models = require('./models/account.js')(Mongoose); 

models.findByUsername('jdoe', (err, result) => { 
+0

'ModelUtils.getModelName()'只是獲取文件的名稱,並將其從'/ models/account.js'轉換爲'Account'。它只是返回一個字符串....如何會導致錯誤的帽子? [Heres the code for it](http://pastebin.com/tLerkVi5) – Justin

+0

也許它與加載所有模型的'/ models/index.js'有關?繼承人文件:http://pastebin.com/D0r8bPpS – Justin

+0

+ zangw,它似乎工作時,我只用一個普通的字符串替換'ModelUtils.getModelName()'...任何想法,爲什麼會這樣?這個函數只是返回一個字符串......我不能想到爲什麼會是這個問題的原因,但顯然是這樣 – Justin

相關問題