我試圖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()
})
爲什麼你需要在賬戶模型中設置組模型?看看給定的代碼,這似乎不是必要的。 'ModelUtils'的目的是什麼? – qqilihq
我實際上已經在本地註釋掉了,這是拋出錯誤。我猜測**可能是賬戶模式需要它,因爲它被引用,但那只是在黑暗中拍攝的。 – Justin