我试图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